FileInputStream in = new FileInputStream("G:\\file\\a/test.txt");
FileOutputStream out= new FileOutputStream("G:\\file\\b/test.txt");
byte[] b = new byte[1024*1024];
int a = 0;
while (true){
a = in.read(b);
if(a == -1){
break;
}
out.write(b,0,b.length);
out.flush();
}
out.close();
in.close();
System.out.println("ok");
两个重要的流是 FileInputStream 和 FileOutputStream
FileInputStream
FileInputStream in = new FileInputStream("[路径]文件名");
也可以使用一个文件对象来创建一个输入流对象来读取文件。我们首先得使用 File() 方法来创建一个文件对象:
File f = new File("[路径]文件名");
InputStream out = new FileInputStream(f);
我们通过public int read(byte[] r) throws IOException{}这个方法来读取文件,需要自己设置一个byte[]数组作为缓冲区域,这个数组的大小由自己设置,会影响到文件的读取速度。
byte[] b = new byte[1024*1024];
FileOutputStream
该类用来创建一个文件并向文件中写数据。
如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。
FileOutputStream out= new FileOutputStream("[路径]文件名");
同样,也可以使用一个文件对象来写文件
File f = new File("[路径]文件名");
OutputStream f = new FileOutputStream(f);
使用public void write( byte[] w)throws IOException{}这个方法来写入文件
用read方法读取的数据放在byte[]数组里,再write进去。
int a = 0;
while (true){
a = in.read(b);
if(a == -1){
break;
}
out.write(b,0,b.length);
out.flush();
}
out.close();
in.close();
这段代码中,int a用来接收read方法的返回值,如果等于-1,说明文件已经读取到了结尾,说明文件读写已完成。
每次write写入之后,需要flush()方法刷新清空缓存区域,以进行下次的读写操作。
当读写完成之后,用close()方法关闭流,释放资源,顺序为先关闭输出流,再关闭输入流。
用字节流进行的一次文件简易读写流程就完成了。