java的io小练习---复制文件到某个路径

 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里了,并且两个文件的大小都是一样的

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值