java的io小练习---复制文件到某个路径
package chapter04;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
*
* @date 2019/10/17 18:20
* @author LINKSINKE
* <p>
* 复制文件C:\aa\aa.exe 至 C:\bb\bb.exe
* </p>
*/
public class CopyFileTest {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("系统退出。请检查参数个数!\r源路径 新路径");
System.exit(1);
}
File path = new File(args[0]);
if (!path.exists()) {
System.err.println("系统退出。源路径不存在");
System.exit(1);
}
File newPath = new File(args[1]);
// 如果新的文件路径不存在就创建
if (!newPath.getParentFile().exists()) {
newPath.getParentFile().mkdirs();
}
InputStream inputFile = new FileInputStream(path);// 需要读取的文件(源路径的文件)
OutputStream outputFile = new FileOutputStream(newPath); // 需要输出的文件(新路径的文件)
int temp = 0; // 文件大小
byte[] readSize = new byte[1024];// 每次读写的文件为1kb
while ((temp = inputFile.read(readSize)) != -1) { // 如果没有读完就继续,一直到读完
outputFile.write(readSize, 0, temp);// 写入的大小,从0开始,每次写入readSize(其实就是每次读入的大小)的大小
}
outputFile.close();
inputFile.close();
System.out.println("文件已复制到"+newPath);
}
}
需要注意一点,如果直接运行上面的程序会出现下面的结果
如果要想成功运行,需要在运行的时候加入参数(也就是args的内容,源路径 新路径),指定args内容,才能,否则一直会在第一个判断语句里退出。(源路径下的文件内容自己准备)
最后看下复制的内容完不完整吧(或者有没有实现复制)
结果:果然C:\aa\aa.exe 复制到了 C:\bb\bb.exe里了,并且两个文件的大小都是一样的