学Java的第33天 文件的复制方式
字节缓冲流:
缓冲输出流 BufferedOutputStream
缓冲输入流 BufferedInputStream
package cn.aaa.copy;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/*
* 文件的复制方式
* 1 字节流 读写单个字节
* 2 字节流 读写字节数组
* 3 字节流缓冲区 读写单个字节
* 4 字节流缓冲区 读写字节数组
* */
public class Copy {
public static void main(String[] args) throws Exception {
long timeStart=System.currentTimeMillis();
copy1(new File("c:\\buffer.txt"),new File("d:\\buffer.txt"));
copy2(new File("c:\\buffer.txt"),new File("c:\\buffer.txt"));
copy3(new File("c:\\buffer.txt"),new File("c:\\buffer.txt"));
copy4(new File("c:\\buffer.txt"),new File("c:\\buffer.txt"));
long timeEnd=System.currentTimeMillis();
System.out.println(timeEnd-timeStart);
}
//4 字节流缓冲区 读写字节数组
public static void copy4(File src, File desc) throws Exception {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(desc));
int len=0;
byte[] b=new byte[1024];
while((len=bis.read(b))!=-1){
bos.write(b,0,len);
}
bis.close();
bos.close();
}
//3 字节流缓冲区 读写单个字节
public static void copy3(File src, File desc) throws Exception {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(desc));
int len=0;
while((len=bis.read())!=-1){
bos.write(len);
}
bis.close();
bos.close();
}
//2 字节流 读写字节数组
public static void copy2(File src,File desc) throws Exception {
FileInputStream fis=new FileInputStream(src);
FileOutputStream fos=new FileOutputStream(desc);
int len=0;
byte[] b=new byte[1024];
while((len=fis.read(b))!=-1){
fos.write(b,0,len);
}
fos.close();
fis.close();
}
//1 字节流 读写单个字节
public static void copy1(File src,File desc) throws Exception {
FileInputStream fis=new FileInputStream(src);
FileOutputStream fos=new FileOutputStream(desc);
int len=0;
while((len=fis.read())!=-1){
fos.write(len);
}
fos.close();
fis.close();
}
}