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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22847805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:21:54  来源:igfitidea点击:

Passing file path as an argument in Java

javacommand-line-arguments

提问by user3495420

I have been working with buffering a file on my local drive to parse and obtain certain data. For test purposes I was easily able to do it this way:

我一直在缓冲本地驱动器上的文件以解析和获取某些数据。出于测试目的,我可以轻松地这样做:

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 file has the following function:

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;
}

Now I want the file path to be passed as a Command line Argument instead. I tried a few things but I am kind of new to this and wasnt able to make it work. Can someone please help and explain what all changes I need to make in order to incorporate that change in my code.

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

回答by peter.petrov

You need to do this:

你需要这样做:

public static void main(String[] args) {
    String path = args[0];
    // ... 
    File CP_file = new File(path);
    // ... 
}        

回答by Konstantin Tarashchanskiy

If you want to replace the hard coded path with one that you are passing via the command line, you should just be able to pass it in as a String. Your code will not read:

如果你想用你通过命令行传递的路径替换硬编码路径,你应该能够将它作为字符串传递。您的代码不会读取:

...
File CP_file = new File(arg[0]);   //Assuming that the path is the first argument
...

Be sure to quote the path on the CLI, especially if it contains white space or other special characters.

请务必在 CLI 上引用路径,尤其是当它包含空格或其他特殊字符时。

回答by Giovani Calota

The complete answer would be something like this :

完整的答案将是这样的:

The below code by path means /etc/dir/fileName.txt

以下代码按路径表示 /etc/dir/fileName.txt

public static void main(String[] args) {
String path = args[0];
// ... 
File CP_file = new File(path);
// ... 

}

}

But if you want to give just a path and from that path your code to read all your files contained by that directory you would require the above to be exported as a jar file code plus a bat file/ script : bat file example :

但是,如果您只想提供一个路径,并从该路径中读取您的代码以读取该目录中包含的所有文件,则需要将上述内容导出为 jar 文件代码和 bat 文件/脚本:bat 文件示例:

FOR %%i IN  (C:/user/dir/*.zip) do (java -cp application.jar;dependencies.jar;...;%%i)

Run the script and your code will run the file / files that are on the path C:/user/dir/*.zip

运行脚本,您的代码将运行路径 C:/user/dir/*.zip 上的文件

回答by walen

Your problem has two sides: how to pass the parameter from the command line, and how to read it inside your code.

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

Passing arguments to a Java program

将参数传递给 Java 程序

All arguments meant for the actual Java class and not for the JVM, should be put afterthe class name, like this:

意味着实际的Java类,而不是在JVM的所有参数,应放的类名,如下所示:

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

Things to watch out for:

需要注意的事项:

  • Slashes /vs backslashes \: since you're on a Windows system, I'd rather use backslashes for your path, specially if you are including the drive letter. Java can work with both variants, but it's better to follow your SO conventions.
  • Double quotes "to allow for spaces: you'll need to enclose your path in double quotes if any directories contain spaces in their names, so just double quote it every time.
  • Remove final backslash: this only applies to directory paths (file paths can't end in a backslash in Windows). If you write a directory path like this: "C:\My path\XYZ\", the last double quote will be included as part of the path, because of the previous backslash escaping it \". Instead, "C:\My path\XYZ"will do fine.
  • 斜杠/与反斜杠\:由于您使用的是 Windows 系统,因此我宁愿使用反斜杠作为您的路径,特别是如果您包含驱动器号。Java 可以使用这两种变体,但最好遵循您的 SO 约定。
  • 双引号"以允许空格:如果任何目录的名称中包含空格,您需要用双引号将路径括起来,所以每次都用双引号引起来。
  • 删除最后的反斜杠:这仅适用于目录路径(Windows 中的文件路径不能以反斜杠结尾)。如果您编写这样的目录路径:"C:\My path\XYZ\",最后一个双引号将作为路径的一部分包含在内,因为前面的反斜杠将它转义\"。相反,"C:\My path\XYZ"会做得很好。

Reading arguments from your main(String[])method

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

Now this one is simple: as others have pointed out, the String with your path should now be in args[0]:

现在这个很简单:正如其他人所指出的,带有您路径的字符串现在应该在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);

        ....
    }
}

I added some null-checking to avoid problems like the ArrayIndexOutOfBoundsyou run into.

我添加了一些空检查以避免像ArrayIndexOutOfBounds您遇到的问题。