Java文件输入输出流实战:读写操作示例
在Java中,我们通常使用FileInputStream和FileOutputStream来进行文件的读写操作。下面是一些具体的操作示例:
- 读取文件:
try (FileInputStream fis = new FileInputStream("example.txt"));) {
byte[] buffer = new byte[1024]; // 一次性读取1KB
int read;
while ((read = fis.read(buffer))) != -1) { // 如果不为空,继续读取
System.out.println(new String(buffer, 0, read))));
}
} catch (IOException e) {
e.printStackTrace();
}
- 写入文件:
注意:在实际使用中,需要处理可能发生的IOException。此外,写文件后记得关闭流。try (FileOutputStream fos = new FileOutputStream("example.txt"));) {
String content = "Hello, World!"; // 要写入的内容
fos.write(content.getBytes()); // 写入内容
fos.flush(); // 清理缓存,确保数据已写入磁盘
} catch (IOException e) {
e.printStackTrace();
}
还没有评论,来说两句吧...