首页 > 解决方案 > 在java中处理cmd中的文件路径

问题描述

我正在尝试使用我的 java 程序从一个文件夹中复制一个文件并通过命令行粘贴到另一个文件夹中,但我遇到了一堆不同的错误。我的代码是

public static void main(String[] args) throws IOException
{
    String src = args[0];
    String dest = args[1];
    String temp[] = src.split("\\");
    String fileName = temp[temp.length-1];
    String data;
    FileReader fr = null;
    BufferedReader br = null;
    FileWriter fw = null;
    PrintWriter pw = null;
    try
    {
        fr = new FileReader(src);
        br = new BufferedReader(fr);
        fw = new FileWriter(dest + "\\" + fileName);
        pw = new PrintWriter(fw);
        data = br.readLine();
        while(data != null)
        {
            pw.println(data);
            data = br.readLine();
        }
    }
    catch(IOException ex)
    {
        System.out.println(ex.getMessage());
    }
}

请告诉我我的代码做错了什么。提前致谢。

这些是我在 cmd https://imgur.com/a/83JvVmP上遇到的错误

标签: javacommand-line-arguments

解决方案


您可以使用 Paths 来获取 de 路径:

public static void main(String[] args) {
    String src = args[0];
    String dest = args[1];

    String fileName = Paths.get(src).getFileName().toString();

    System.out.println("fileName:" + fileName);

    String data;
    FileReader fr = null;
    BufferedReader br = null;
    FileWriter fw = null;
    PrintWriter pw = null;
    try {
        fr = new FileReader(src);
        br = new BufferedReader(fr);
        fw = new FileWriter(dest + "\\" + fileName);
        pw = new PrintWriter(fw);
        data = br.readLine();
        while (data != null) {
            pw.println(data);
            data = br.readLine();
        }
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
}

我在 Eclipse 中尝试了这个,并使用了一个 Jar,并且工作正常:

在此处输入图像描述


推荐阅读