java - 在 Java 中将文件路径作为参数传递

标签 java command-line-arguments

我一直在努力在我的本地驱动器上缓冲一个文件来解析和获取某些数据。出于测试目的,我很容易做到这一点:

public static void main(String[] args) {

    fileReader fr = new fileReader();
    getList lists = new getList();


    File CP_file = new File("C:/Users/XYZ/workspace/Customer_Product_info.txt");
    int count = fr.fileSizeInLines(CP_file);
    System.out.println("Total number of lines in the file are: "+count);

    List<String> lines = fr.strReader(CP_file);

    ....

}

}

fileReader.java 文件具有以下功能:

public List<String> strReader (File in)
{
    List<String> totLines = new ArrayList<String>();

    try
    {
        BufferedReader br = new BufferedReader(new FileReader(in));
        String line;
        while ((line = br.readLine()) != null)
        {
            totLines.add(line);
        }
        br.close();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //String result = null;

    return totLines;
}

现在我希望将文件路径作为命令行参数传递。我尝试了一些东西,但我对此有点陌生,无法让它发挥作用。有人可以帮助并解释我需要进行哪些更改才能将这些更改合并到我的代码中。

最佳答案

您的问题有两个方面:如何从命令行传递参数,以及如何在代码中读取它。

将参数传递给 Java 程序

所有用于实际 Java 类而非 JVM 的参数都应放在类名之后,如下所示:

C:\YOUR\WORKSPACE> java your.package.YouMainClass "C:\Users\XYZ\workspace\Customer_Product_info.txt"`

注意事项:

  • 斜杠 / 与反斜杠 \:由于您使用的是 Windows 系统,我宁愿在您的路径中使用反斜杠,特别是如果您包含驱动器号. Java 可以使用这两种变体,但最好遵循您的 SO 约定。
  • 双引号 " 允许有空格:如果任何目录的名称中包含空格,您需要用双引号将路径括起来,所以每次都用双引号引起来。
  • 删除最后的反斜杠:这仅适用于目录路径(在 Windows 中文件路径不能以反斜杠结尾)。如果您编写这样的目录路径:"C:\My path\XYZ\",最后一个双引号将作为路径的一部分包含在内,因为前面的反斜杠将其转义 \"。相反,"C:\My path\XYZ" 会很好。

从您的main(String[]) 方法中读取参数

现在这个很简单:正如其他人所指出的,带有您的路径的字符串现在应该在 args[0] 中:

public static void main(String[] args) {

    fileReader fr = new fileReader();
    getList lists = new getList();

    if (args[0] == null || args[0].trim().isEmpty()) {
        System.out.println("You need to specify a path!");
        return;
    } else {
        File CP_file = new File(args[0]);
        int count = fr.fileSizeInLines(CP_file);
        System.out.println("Total number of lines in the file are: "+count);

        List<String> lines = fr.strReader(CP_file);

        ....
    }
}

我添加了一些空值检查以避免您遇到诸如 ArrayIndexOutOfBounds 之类的问题。

关于java - 在 Java 中将文件路径作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22847805/

相关文章:

Java swing JTable RowFilter 忽略符号

python - 为什么 subprocess.Popen 参数长度限制小于操作系统报告的长度?

delphi - 为什么当应用程序由 IDE 与启动器启动时,命令行参数的数量会发生变化?

python - 使用 IDLE 将命令行参数传递给 Python 程序?

java - 解析 HTML - 仅获取表行的子集

java - 编写这个函数的更好方法是什么?

java - Java 中 wait() 方法的异常

python - lua相当于shlex?

java - Java 中 Heisenbugs 的可能和不太可能的原因?