从命令行中读入一个文件名,判断该文件是否存在。如果该文件存在,则在原文件相同路径下创建一 个文件名为“copy_原文件名”的新文件,该文件内容为原文件的拷贝

发布时间 2023-04-09 15:57:49作者: ZuaMagee

例如:读入 /home/java/photo.jpg 则创建一个文件 /home/java/copy_photo.jpg 新文件内容和原文件内容 相同

package io.homework;

import java.io.*;
import java.util.Scanner;

public class q23 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        File file = new File(s);
        boolean flag = file.isFile();
        System.out.println(flag);
        if (flag) {
            try(InputStream is = new FileInputStream(s);
                BufferedInputStream bis = new BufferedInputStream(is);
                OutputStream os = new FileOutputStream("copy_"+s);
                BufferedOutputStream bos = new BufferedOutputStream(os)) {
                byte[] bs = new byte[1024];
                while (true) {
                    int len = bis.read(bs);
                    if (len == -1) break;
                    bos.write(bs);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}