文件拷贝需要使用I/O流。主要记住核心的6行代码就行
逐个字节拷贝,文件大时很慢,不推荐使用
public static void test() throws IOException {
//创建输入流对象
FileInputStream fis = new FileInputStream("C:/Users/DG02/Desktop/test.txt");
//创建输出流对象
FileOutputStream fos = new FileOutputStream("C:/Users/DG02/Desktop/test1.txt");
int b;
//读取文件并写入
while((b=fis.read()) != -1){
fos.write(b);
}
//关闭输入流对象
fis.close();
//关闭输出流对象
fos.close();
}
需要注意的是,不能int b = fis.read(),然后直接b!=-1 这样会死循环。
通过一个和文件字节大小一样的数组进行拷贝
public static void test1() throws IOException {
//创建输入流对象
FileInputStream fis = new FileInputStream("C:/Users/DG02/Desktop/test.txt");
//创建输出流对象
FileOutputStream fos = new FileOutputStream("C:/Users/DG02/Desktop/test1.txt");
//创建一个字节数值,数组大小与要拷贝的文件字节大小一致
byte[] arr = new byte[fis.available()];
//把读取的文件字节全部放入数组中
fis.read(arr);
//把数组的字节写入到文件
fos.write(arr);
fis.close();
fos.close();
}
available()会返回文件字节大小
先把文件字节全部读取到一个字节数组中,然后一次性写入
通过缓冲写入
public static void test2() throws IOException {
//创建输入流对象
FileInputStream fis = new FileInputStream("C:/Users/DG02/Desktop/test.txt");
//创建输出流对象
FileOutputStream fos = new FileOutputStream("C:/Users/DG02/Desktop/test1.txt");
//对输入流进行包装,创建读取缓冲区
BufferedInputStream bis = new BufferedInputStream(fis);
//对输出流进行包装,创建写入缓冲区
BufferedOutputStream bos = new BufferedOutputStream(fos);
//读取缓冲区的字节,当字节不为-1,写入
int b;
while ((b=bis.read())!=-1){
bos.write(b);
}
//关闭输入流缓冲区
bis.close();
//关闭输出流缓冲区
bos.close();
}
源码中缓冲区是一个默认8192大小的字节数。每次都会从文件读取这样大小的内容到缓冲区。然后把缓冲区的内容读完后,才会再次去读取文件,直到文件内容结束。写入也是,先把内容写入到缓冲区。直到缓冲区满了,再写入文件。