编写一个应用程序实现文件的复制。使用格式:java Copy 源文件目标文件,功能是将源文件的内容复制到目标文件。

import java.io.*;

public class Main {

    public static void main(String[] args) {
        new Main().runFunction();
    }

    private void runFunction() {

        System.out.println("文件复制程序开始:");

        long startTime = System.currentTimeMillis();
        File originalFile = new File("d:\\java\\jdk1.8中文百度.CHM");
        File targetFile = new File("d:\\java\\jdk1.8中文百度(副本).CHM");
        BufferedInputStream in = null;
        BufferedOutputStream out = null;

        System.out.println("源文件目录:\t" + originalFile.getAbsolutePath());
        System.out.println("目标文件为:\t" + targetFile.getAbsolutePath());


        try {

            in = new BufferedInputStream(new FileInputStream(originalFile));
            out = new BufferedOutputStream(new FileOutputStream(targetFile));
            byte[] data = new byte[1024];
            int len = 0;
            while ((len = in.read(data)) != -1) {
                out.write(data, 0, len);
                out.flush();
            }

        }catch(IOException e) {
            e.getMessage();
            throw new RuntimeException("\n程序复制时出现错误,请重试");
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
                }
                catch(IOException error) {
                    error.getMessage();
                    throw new RuntimeException("\n流通道关闭失败,请重试");
                }
            }
        String end = targetFile.exists() == true ? "文件复制成功" : "文件复制失败";
        System.out.println("\n" + end + "\n总共耗时:\t" + (System.currentTimeMillis() - startTime) + "ms");
        }

    }

0

Leave a Reply

Your email address will not be published.