(File类、字节流、桥转换流、字符流)从命令行中读入一个文件名,判断该文件是否存在。如果该文件存在,则在原文件相同路径下创建一个文 件名为“copy_原文件名”的新文件,该文件内容为原文件的拷贝

题目


(File类、字节流、桥转换流、字符流)
从命令行中读入一个文件名,判断该文件是否存在。如果该文件存在,则在原文件相同路径下创建一个文
件名为“copy_原文件名”的新文件,该文件内容为原文件的拷贝。例如:读入/home/java/photo.jpg
则创建一个文件/home/java/copy_photo.jpg新文件内容和原文件内容相同。


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

public class TestFileCopy {
    /**
     * 创建新文件,并复制原文件中的内容
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一个文件名:");
        String fileName = input.next();
        boolean result = false;
        try {
            result = copyFile(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);//创建成功
    }

    //复制文件
    private static boolean copyFile(String fileName) throws IOException {
        File copyFile = createFile(fileName);
        if (copyFile != null) {//非空判断
            InputStream is = new FileInputStream(fileName);//读源文件
            OutputStream os = new FileOutputStream(copyFile);//写到复制出的文件中
            int len = 0;
            while ((len = is.read()) != -1) {
                os.write(len);
            }
            is.close();
            os.close();
            return true;
        }
        return false;
    }

    //创建文件操作
    private static File createFile(String fileName) throws IOException {
        File file = new File(fileName);
        if (file.exists()) {
            System.out.println(file.getParent());//得到父路径,拼接copy_后拼接文件名
            File copyFile = new File(file.getParent() + "\\copy_" + file.getName());
            copyFile.createNewFile();//创建文件
            return copyFile;//返回创建后的文件
        } else {
            System.out.println("原文件不存在");
        }
        return null;
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了119 篇原创文章 · 获赞 179 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_44170221/article/details/104934016