思路:通过FileInputStream类的对象将原文件与其对象关联,将原文件内容读取到内存中,然后通过FileOutputStream类的对象将内存中的数据写入到磁盘中
import java.io.*;
public class Test3 {
public static void method(File source,File copy)
{
long time1=System.currentTimeMillis();
try (InputStream inputStream=new FileInputStream(source);
OutputStream outputStream=new FileOutputStream(new File(copy,source.getName()))){
byte[] bytes=new byte[1024*10];
int i;
while ((i=inputStream.read(bytes,0,bytes.length))!=-1)//只写一个参数bytes也可
{
outputStream.write(bytes,0,i);//形参建议写全
}
System.out.println("复制完成");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
long time2=System.currentTimeMillis();
System.out.println("用时:"+(time2-time1)+"毫秒");
}
public static void main(String[] args) {
String source="D:\\Downloads\\jdk api 1.8_google.CHM";
String copy="D:\\";
method(new File(source),new File(copy));
}
}
一、inputStream对象将source文件的内容读到内存中,outputStream对象将内存中的数据写入到copy文件中;
二、需要注意,copy文件对象为一个目录,文件并不存在(String copy=“D:\”;),因此在将outputStream对象实例化时,构造器中应新建一个File类的对象,new File(copy,source.getName())
从API文档中可以看出,File类其中一个构造写法为File(File parent, String child) ,在本例中parent即为copy复制文件,child即为source的name。本例使复制文件同原文件同名。