Java字节流复制文件
普通字节流
package com.xmaven;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @ClassName FileInputDemo
* @Description TODO
* @Author Ambition
* @Date 2021/1/20 15:39
* @Version 1.0.0
**/
public class FileInputDemo {
public static void main(String[] args) {
try {
// 定义读取的文件
FileInputStream fis = new FileInputStream("test.txt");
// 定义输出的文件
FileOutputStream fos = new FileOutputStream("testcopy.txt");
int n = 0;
// 定义缓冲区
byte[] b = new byte[1024];
// 判断是否获取到文件的末尾 -1表示读取到文件末尾
while ((n = fis.read(b)) != -1) {
// 第一个参数写入的数据
// 第二个参数数据中的起始偏移量
// 第三个参数要写入的字节数
fos.write(b, 0, n);
}
fos.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
缓冲字节流
package com.xmaven;
import java.io.*;
/**
* @ClassName BufferedDemo
* @Description TODO
* @Author Ambition
* @Date 2021/1/20 15:48
* @Version 1.0.0
**/
public class BufferedDemo {
public static void main(String[] args) {
try {
// 定义读取的源文件
FileInputStream fis = new FileInputStream("test.txt");
// 放入到缓冲字输入节流中
BufferedInputStream bis = new BufferedInputStream(fis);
// 定义一个输出的文件
FileOutputStream fos = new FileOutputStream("testcopy.txt");
// 把这个文件放入到缓冲字输出节流中
BufferedOutputStream bos = new BufferedOutputStream(fos);
int n = 0;
byte[] b = new byte[1024];
while ((n = bis.read(b)) != -1) {
bos.write(b, 0, n);
}
/*
* flush()方法主要用来清空缓冲区。当缓冲区被填满时就会自动执行写操作,但是当缓冲区不满时,
* 就不会执行写操作。所以,当缓冲区未被填满但要执行写操作时就要强制清空缓冲区
* */
bos.flush();
bos.close();
fos.close();
bis.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
评论区