我们先上一个字节输入输出流的复制文件,代码:
public static void main(String[] args) {
FileInputStream in = null;
FileOutputStream o = null;
long s = System.currentTimeMillis();
try {
in = new FileInputStream("F:\\a\\Sams teach yourself SQL in 10 minutes,4th edition.pdf");
o = new FileOutputStream("f:\\a\\1.pdf");
byte[] b = new byte[1024*5];
int len = 0;
while((len =in.read(b))!=-1) {
o.write(b);
}
}catch(IOException e) {
System.out.println("文件写入失败!");
}finally {
try {
o.close();
}catch(IOException e) {
System.out.println("文件关闭失败!");
}finally {
try {
in.close();
}catch(IOException e) {
System.out.println("文件关闭失败");
}
}
}
long e = System.currentTimeMillis();
System.out.println(e-s);
}
in = new FileInputStream("F:\\a\\Sams teach yourself SQL in 10 minutes,4th edition.pdf");
这句话是我们打算复制的文件,什么格式的都行,我们选择是pdf格式的
o = new FileOutputStream("f:\\a\\1.pdf");
这句话,是我们打算复制到的地方及文件重命名
byte[] b = new byte[1024*5];
运用字节数组读取,然后输出。
while((len =in.read(b))!=-1) {
当len不是-1的时候,说明,in一直在读取。
o.write(b);
把b数组中读取的数据取出来,写入o所代表的文件中(没有自动创建)
接下来就是异常及关闭流文件,不多说。下面:
long s = System.currentTimeMillis();
long e = System.currentTimeMillis();
System.out.println(e-s);
这三句是我们为了测试,复制用多长时间而设置的,与读取文件无关。
结果:
162
162毫秒(0.162秒)
读取很快就完成了,这样就完整的在别处复制了一份文件。