使用java进行文件的复制我们需要两步:
1.在指定路径寻找原文件,若指定路径没有原文件,我们需要在指定路径创建文件,然后读取文件中的信息(每次读取1bit信息)
2.在指定路径寻找目标文件,若指定路径没有目标文件,我们需要在指定路径创建目标文件,然后循环多次写入原文件中的信息,直至全部写入位置
1.复制小型文件
public static void copyFile() throws IOException {
String fromPath = "e://1.mp4";
File fromFile = new File(fromPath);
//如果文件不存在则创建文件
if (!fromFile.exists()) {
fromFile.createNewFile();
}
String goPath = "e://1_new.mp4";
File goFile = new File(goPath);
//如果文件不存在则创建文件
if (!goFile.exists()) {
goFile.createNewFile();
}
//创建输入流,读取fromFile
InputStream in = new FileInputStream(fromFile);
//创建输入流,写入到goFile
OutputStream out = new FileOutputStream(goFile);
int i = 0;
while ((i = in.read()) != -1)
{
char j = (char) i;
out.write(j);
}
out.flush();
out.close();
in.close();
System.out.println("文件复制结束!!!"); }
2.复制大型文件
与复制小型文件不同的是,我们需要每次从原文件读取1024bit的信息用于信息的传递,直至将信息全部写入目标文件
public static void copyFile2() throws IOException {
String fromPath = "e://1.mp4";
File fromFile = new File(fromPath);
//如果文件不存在则创建文件
if (!fromFile.exists()) {
fromFile.createNewFile();
}
String goPath = "e://1_new.mp4";
File goFile = new File(goPath);
//如果文件不存在则创建文件
if (!goFile.exists()) {
goFile.createNewFile();
}
//创建输入流,读取fromFile
InputStream in = new FileInputStream(fromFile);
//创建输入流,写入到goFile
OutputStream out = new FileOutputStream(goFile);
byte[] buf = new byte[2048];
int i = 0;
while ((i = in.read(buf)) != -1) {
out.write(buf, 0, i);
out.flush();
}
out.close();
in.close();
System.out.println("文件复制结束!!!");
}