上一次总结了使用字节流对文件进行读写,然而现实使用中,我们常常会进行的是大文件的读写,那么此时使用上节课的方式进行读写就不太好,因为你会不知道文件的大小,所以我们可以使用循环配合字节流来对文件进行读写:
//第一步骤:导入类
import java.io.*;
class Test{
public static void main(String args[]){
//声明输入流引用
FileInputStream fis = null;
//声明输出流引用
FileOutputStream fos = null;
try{
//生成代表输入流的对象
fis = new FileInputStream("d:/work/src/from.txt");
//生成代表输出流的对象
fos = new FileOutputStream("d:/work/src/to.txt");
//生成一个字节数组
byte [] buffer = new byte[1024];
while(true){
//调用输入对象的read方法,读取字节数组的数据
int temp = fis.read(buffer,0,buffer.length);
if(temp == -1){
break;
}
//调用输出流的write方法,写入字节数组的数据
fos.write(buffer,0,temp);
}
}
catch(Exception e){
System.out.println(e);
}
finally{
try {
fis.close();
fos.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
}
然后介绍一下字符流,字符流和字节流并没有什么区别,只是对文件的读取方式是用字符的形式而已,具体代码如下:
import java.io.*;
public class TestChar{
public static void main(String argsp[]){
FileReader fr = null;
FileWriter fw = null;
try{
fr = new FileReader("d:/work/src/from.txt");
fw = new FileWriter("d:/work/src/to.txt");
char [] buffer = new char[100];
int temp = fr.read(buffer,0,buffer.length);
fw.write(buffer,0,temp);
}
catch(Exception e){
System.out.println(e);
}
finally{
try {
fr.close();
fw.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
}