如何利用Java的IO流进行文件读写操作
在Java中,我们可以使用java.io
包中的类来进行文件读写操作。下面是一些基本的例子:
文件读取:
FileInputStream
:打开一个字节输入流,用于从磁盘文件或网络读取数据。FileInputStream fis = new FileInputStream("example.txt");
// 从流中读取数据
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))) != -1) {
// 处理读取的数据
}
fis.close(); // 关闭文件流
文件写入:
FileOutputStream
:打开一个字节输出流,用于将数据写入磁盘文件或网络。FileOutputStream fos = new FileOutputStream("example.txt");
// 将数据写入流
byte[] buffer = new byte[1024];
int length;
String dataToWrite = "Hello, World!";
while ((length = dataToWrite.getBytes().length)) != -1) {
fos.write(buffer, 0, length);
// 下一次循环可以写入更多数据
}
fos.close(); // 关闭文件流
以上就是使用Java的IO流进行文件读写的基本操作。
还没有评论,来说两句吧...