如何在Java中使用IO流函数进行数据流处理
如何在Java中使用IO流函数进行数据流处理
在Java编程中,IO流是一种非常重要的概念,它是处理输入和输出的基本方式之一。IO流被用于读取文件、网络编程以及与外部设备交互的场景中。本文将介绍如何在Java中使用IO流函数进行数据流处理,并给出具体的代码示例。
读取文件示例:
import java.io.FileInputStream; import java.io.IOException; public class ByteStreamExample { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("input.txt"); int data; while ((data = fis.read()) != -1) { System.out.print((char) data); } fis.close(); } catch (IOException e) { e.printStackTrace(); } } }登录后复制
import java.io.FileOutputStream; import java.io.IOException; public class ByteStreamExample { public static void main(String[] args) { try { FileOutputStream fos = new FileOutputStream("output.txt"); String data = "Hello, World!"; byte[] bytes = data.getBytes(); fos.write(bytes); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }登录后复制
读取文件示例:
import java.io.FileReader; import java.io.IOException; public class CharacterStreamExample { public static void main(String[] args) { try { FileReader reader = new FileReader("input.txt"); int data; while ((data = reader.read()) != -1) { System.out.print((char) data); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } }登录后复制
import java.io.FileWriter; import java.io.IOException; public class CharacterStreamExample { public static void main(String[] args) { try { FileWriter writer = new FileWriter("output.txt"); String data = "你好,世界!"; writer.write(data); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }登录后复制
使用缓冲流读取文件示例:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedStreamExample { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader("input.txt")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } }登录后复制
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedStreamExample { public static void main(String[] args) { try { BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt")); String data = "Hello, World!"; writer.write(data); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }登录后复制