如何在Java中使用IO流来进行文件读写操作?
发布时间:2023-06-05 20:49:20
Java中常用的IO操作有字节流和字符流两种,它们都可以用于文件读写操作。下面分别介绍如何使用它们进行文件读写。
一、字节流
1.1 文件读操作
使用FileInputStream类来读取文件的字节流。其构造方法接受一个文件路径作为参数,示例代码如下:
FileInputStream fis = new FileInputStream("D:\\test.txt");
打开文件后,调用read()方法来读取文件的内容,每次读取一个字节。当读取到文件结尾时,read()方法会返回-1,示例代码如下:
int n = fis.read();
while(n != -1){
System.out.print((char)n);
n = fis.read();
}
读取完毕后,要关闭流,示例代码如下:
fis.close();
1.2 文件写操作
使用FileOutputStream类来写入文件。其构造方法接受一个文件路径作为参数,示例代码如下:
FileOutputStream fos = new FileOutputStream("D:\\test.txt");
写入内容的方法有两个:
1. write(byte[] b):写入整个字节数组。
2. write(int b):写入一个字节。
示例代码如下:
String str = "Hello world!";
byte[] b = str.getBytes();
fos.write(b);
fos.write('
');
fos.write('A');
fos.close();
二、字符流
2.1 文件读操作
使用FileReader类来读取文件的字符流。其构造方法接受一个文件路径作为参数,示例代码如下:
FileReader fr = new FileReader("D:\\test.txt");
读取文件的方法与字节流类似,不同的是每次读取一个字符。示例代码如下:
int n = fr.read();
while(n != -1){
System.out.print((char)n);
n = fr.read();
}
2.2 文件写操作
使用FileWriter类来写入文件。其构造方法接受一个文件路径作为参数,示例代码如下:
FileWriter fw = new FileWriter("D:\\test.txt");
写入内容的方法同样有两个:
1. write(char[] cbuf):写入整个字符数组。
2. write(int c):写入一个字符。
示例代码如下:
String str = "Hello world!";
char[] cbuf = str.toCharArray();
fw.write(cbuf);
fw.write('
');
fw.write('A');
fw.close();
三、复制文件
使用字节流来进行文件复制的示例代码如下:
FileInputStream fis = new FileInputStream("D:\\test1.txt");
FileOutputStream fos = new FileOutputStream("D:\\test2.txt");
int n = fis.read();
while(n != -1){
fos.write(n);
n = fis.read();
}
fis.close();
fos.close();
使用字符流来进行文件复制的示例代码如下:
FileReader fr = new FileReader("D:\\test1.txt");
FileWriter fw = new FileWriter("D:\\test2.txt");
int n = fr.read();
while(n != -1){
fw.write(n);
n = fr.read();
}
fr.close();
fw.close();
以上是Java中使用IO流进行文件读写操作的相关内容。需要注意的是,读写完成后一定要关闭流,否则会导致资源泄漏。另外,在读写过程中可能会出现IOException异常,需要进行处理。
