在Java中将文件路径作为参数传递
我一直在缓冲本地驱动器上的文件来解析并获取某些数据。 出于测试目的,我很容易就能这样做:
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 lines = fr.strReader(CP_file); .... } }
fileReader.java文件具有以下function:
public List strReader (File in) { List totLines = new ArrayList(); 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; }
现在我希望文件路径作为命令行参数传递。 我尝试了一些东西,但我对此并不熟悉并且无法使其正常工作。 有人可以帮助解释我需要做出的所有更改,以便将更改合并到我的代码中。
你需要这样做:
public static void main(String[] args) { String path = args[0]; // ... File CP_file = new File(path); // ... }
如果要将硬编码路径替换为通过命令行传递的路径,则应该能够将其作为String传递。 您的代码不会读取:
... File CP_file = new File(arg[0]); //Assuming that the path is the first argument ...
请务必在CLI上引用路径,特别是如果它包含空格或其他特殊字符。
完整的答案是这样的:
以下代码的路径表示/etc/dir/fileName.txt
public static void main(String[] args) { String path = args[0]; // ... File CP_file = new File(path); // ...
}
但是如果你想只提供一个路径,并且从那个路径你的代码读取该目录包含的所有文件,你需要将上面的内容导出为jar文件代码加上bat文件/脚本:bat文件示例:
FOR %%i IN (C:/user/dir/*.zip) do (java -cp application.jar;dependencies.jar;...;%%i)
运行脚本,您的代码将运行路径C:/ user / dir / * .zip上的文件/文件
您的问题有两个方面:如何从命令行传递参数,以及如何在代码中读取它。
将参数传递给Java程序
所有参数都是针对实际的Java类而不是针对JVM的,应该放在类名后面 ,如下所示:
C:\YOUR\WORKSPACE> java your.package.YouMainClass "C:\Users\XYZ\workspace\Customer_Product_info.txt"`
需要注意的事项:
- 斜杠
/
vs反斜杠\
:因为你在Windows系统上,我宁愿使用反斜杠作为你的路径,特别是如果你包括驱动器号。 Java可以使用这两种变体,但最好遵循您的SO约定。 - 双引号
"
允许空格:如果任何目录的名称中包含空格,则需要将路径括在双引号中,因此每次都要双引号。 - 删除最后的反斜杠:这仅适用于目录路径(文件路径不能以Windows中的反斜杠结尾)。 如果你编写一个这样的目录路径:
"C:\My path\XYZ\"
,最后的双引号将作为路径的一部分包含在内,因为前面的反斜杠转义它\"
。而是,"C:\My path\XYZ"
会很好。
从main(String[])
方法读取参数
现在这个很简单:正如其他人指出的那样,带有路径的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 lines = fr.strReader(CP_file); .... } }
我添加了一些空值检查,以避免遇到像您遇到的ArrayIndexOutOfBounds
类的问题。