Java如何创建IO
创建输入输出(IO)流的方法
在Java中,IO操作主要通过java.io包中的类实现。以下是常见的IO流创建方式:
文件输入流(FileInputStream)
FileInputStream fis = new FileInputStream("input.txt");
文件输出流(FileOutputStream)
FileOutputStream fos = new FileOutputStream("output.txt");
缓冲输入流(BufferedReader)
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
缓冲输出流(BufferedWriter)
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
使用NIO进行IO操作
Java NIO(New IO)提供了更高效的IO处理方式:
通过Path和Files类读写文件
Path path = Paths.get("file.txt");
byte[] fileBytes = Files.readAllBytes(path);
Files.write(path, "content".getBytes());
使用Channel进行文件操作
FileChannel channel = FileChannel.open(Paths.get("file.txt"), StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
对象序列化与反序列化
Java提供了对象IO功能:
对象输出流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(myObject);
对象输入流
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
MyClass obj = (MyClass) ois.readObject();
关闭资源的最佳实践
使用try-with-resources语句确保资源自动关闭:
try (FileInputStream fis = new FileInputStream("file.txt");
FileOutputStream fos = new FileOutputStream("output.txt")) {
// IO操作代码
}
字符编码处理
指定字符编码处理文本文件:

Reader reader = new InputStreamReader(new FileInputStream("file.txt"), "UTF-8");
Writer writer = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8");
以上方法涵盖了Java中常见的IO操作方式,从基本的字节流到高级的NIO操作。根据具体需求选择合适的IO类和方法可以提高程序效率和可维护性。




