java如何提供io
Java IO 基础类库
Java 提供了丰富的 IO 类库,主要位于 java.io 包中。核心类包括:
InputStream/OutputStream:字节流基类Reader/Writer:字符流基类File:文件系统操作类
字节流适用于二进制数据读写,字符流针对文本数据优化,自动处理编码转换。
文件读写操作
使用 FileInputStream 读取文件:
try (InputStream in = new FileInputStream("test.txt")) {
int data;
while ((data = in.read()) != -1) {
System.out.print((char) data);
}
}
使用 FileOutputStream 写入文件:
try (OutputStream out = new FileOutputStream("output.txt")) {
String content = "Hello World";
out.write(content.getBytes());
}
缓冲流提高性能
通过包装缓冲流减少实际IO操作次数:
// 缓冲字节流
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
}
字符流与编码处理
指定字符编码处理文本文件:
try (Reader reader = new InputStreamReader(new FileInputStream("text.txt"), "UTF-8");
Writer writer = new OutputStreamWriter(new FileOutputStream("out.txt"), "UTF-8")) {
char[] buffer = new char[1024];
int len;
while ((len = reader.read(buffer)) != -1) {
writer.write(buffer, 0, len);
}
}
NIO 新IO包
Java NIO 提供更高效的IO处理:
Path path = Paths.get("file.txt");
try (SeekableByteChannel channel = Files.newByteChannel(path, StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (channel.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear();
}
}
文件系统操作
使用 Files 工具类简化操作:

// 读取所有行
List<String> lines = Files.readAllLines(Paths.get("data.txt"));
// 写入文件
Files.write(Paths.get("output.txt"), "content".getBytes());
// 复制文件
Files.copy(Paths.get("src.txt"), Paths.get("dest.txt"));






