Java 实现文件拷贝粘贴
思路
- 创建输入流对象
- 创建输出流对象
- 读写字节流,复制文件
此方法适合一切文件的复制粘贴,因为所有文件底层都是字节
代码
public class CopyDemo {
public static void main(String[] args) throws Exception {
try {
//1.创建文件输入流管道,这里填写文件路径
FileInputStream fis = new FileInputStream("D:\\workspace\\test1.mp4");
//2.创建文件输出流管道
FileOutputStream fos = new FileOutputStream("D:\\workspace\\idea\\testspace2\\test2.mp4");
//3.输入字节流和写字节流
//使用readAllBytes,有风险,当读取文件过大的时候容,可能会出现内存不足,导致堆溢出。
//byte[] bytes = fis.readAllBytes();
byte[] bytes = new byte[1024];
int len=0;
while((len=fis.read(bytes))!=-1){
//读多少,写多少
fos.write(bytes,0,len);
}
//4.释放资源,clos释放时自动flush
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
优化版本,这种方式会自动释放资源,在jdk7里面提出来的
public static void main(String[] args) {
try (
//1.创建文件输入流管道
FileInputStream fis = new FileInputStream("D:\\workspace\\test1.mp4");
//2.创建文件输出流管道
FileOutputStream fos = new FileOutputStream("D:\\workspace\\idea\\testspace2\\test2.mp4");
){
//3.输入字节流和写字节流
//使用readAllBytes,有风险,当读取文件过大的时候容,可能会出现内存不足,导致堆溢出。
//byte[] bytes = fis.readAllBytes();
byte[] bytes = new byte[1024];
int len=0;
while((len=fis.read(bytes))!=-1){
//读多少,写多少
fos.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
}