java中文件拷贝操作

编写一个文件的拷贝程序,可以实现任意的文件拷贝操作,通过初始化参数输入拷贝源文件路径以及拷贝的目标文件的路径。不考虑类的设计。

如果想要实现这种拷贝的操作,可以有以下两种实现思路

  • 思路一:开辟一个数组,将所需要拷贝的内容读取到数组之中,而后一次性输出到目标路径中。
  • 思路二:采用边度边写方式进行拷贝,不是一次性读取。

范例:

package lisy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyDemo {
    public static void main(String[] args) throws Exception {
        //如果要执行拷贝命令,则必须初始化参数传递源文件路径以及目标文件路径
        if(args.length != 2) {//参数内容必须是两个
            System.out.println("错误的命令,格式为:CopyDemo 源文件路径 目标文件路径");
            System.exit(1);//退出程序
        }
        //如果现在有参数了。那么还需要验证源文件是否存在
        File inFile = new File(args[0]);
        if(!inFile.exists()) {
            System.out.println("路径错误,请确定源文件路径正确。");
            System.exit(1);
        }
        //如果拷贝的目标文件存在,则也不应该进行拷贝
        File outFile = new File(args[1]);
        if(outFile.exists()) {//目标文件已经存在
            System.out.println("拷贝的路径已经存在,请更换路径");
            System.exit(1);
        }
        long start = System.currentTimeMillis();
        InputStream in = new FileInputStream(inFile);
        OutputStream out = new FileOutputStream(outFile);
        copy(in, out);//开始实现文件拷贝操作
        in.close();
        out.close();
        long end = System.currentTimeMillis();
        System.out.println("花费的时间啊:"+(end - start));
    }
    public static void copy(InputStream input,OutputStream output) throws Exception {
        int temp = 0;//保存每次读取的数量
        byte data [] = new byte[1024];
        //数据向数组之中进行读取
        while((temp = input.read()) !=-1) {//每次读取一个字节
            output.write(data,0,temp);//输出数组
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41112517/article/details/80357822
今日推荐