Java实现将一个文件的复制到另一个文件中去(字节流形式...可复制文本,视频,音频等文件)
程序员文章站
2022-03-05 14:33:00
...
实现代码如下
package FileRead;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("D:\\file.mp4");
FileOutputStream fileOutputStream = new FileOutputStream("D:\\myFile\\file.mp4");//使用时必须先创建文件夹myfile
int b;
while ((b = fileInputStream.read()) != -1){
fileOutputStream.write(b);
}
fileInputStream.close();
fileOutputStream.close();
}
}
上述的实现代码只能对小型文件进行复制,但是像音频或者视频的话,一般文件较大,复制消耗的时间相当大,所以有了下面的改进版
package FileRead;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
// FileInputStream fileInputStream = new FileInputStream("D:\\file.mp4");
// FileOutputStream fileOutputStream = new FileOutputStream("D:\\myFile\\file.mp4");
// int b;
// while ((b = fileInputStream.read()) != -1){
// fileOutputStream.write(b);
// }
//
// fileInputStream.close();
// fileOutputStream.close();
FileInputStream fileInputStream = new FileInputStream("D:\\file.mp4");
FileOutputStream fileOutputStream = new FileOutputStream("D:\\myFile\\file.mp4");
byte btye[] = new byte[1024];
int len;
while ((len = fileInputStream.read(btye)) != -1){
fileOutputStream.write(btye,0,len);
}
fileInputStream.close();
fileOutputStream.close();
}
}