在 java 的 FileReader 中使用 space 作为命令行参数传递目录
Passing directory with space as command line argument in FileReader in java
try (BufferedReader b = new BufferedReader(new FileReader(args[0]))) {
System.out.println("Reading from file :" + args[0]);
String s = null;
while ((s = b.readLine()) != null) {
System.out.println(s);
}
} catch (ArrayIndexOutOfBoundsException a) {
System.out.println("No file specified, quitting !");
} catch (FileNotFoundException fe) {
System.out.println("File not found :" + args[0]);
} catch (IOException ie) {
System.out.println("Error reading file : " + ie.getMessage());
}
这里的 args[0] 是:G:\Lab Practice\file.txt
输出:
找不到文件 :G:\Lab
这是因为路径中有一个space。
我也试过用 args[0]+args[1] 替换 args[0] 但它没有用。
谁能帮我解决这个问题?
只需将参数放在引号中即可:
java Class "G:\Lab Practice\file.txt"
如果没有 space,它会将每个参数视为 args
数组中的单独参数 - 因此 G:\Lab
是 args[0]
而 Practice\file.txt
是 args[1]
在你的例子中。
来自docs:
This is because the space character separates command-line arguments.
To have Drink, Hot, and Java interpreted as a single argument, the
user would join them by enclosing them within quotation marks.
我假设你这样调用你的程序:
java -jar application.jar G:\Lab Practice\file.txt
这只是意味着您有两个参数 - G:\Lab
(在 args[0]
中)和 Practice\file.txt
(在 args[1]
中)。现在两者都没有任何空格。
您需要在调用中添加一些引号:
java -jar application.jar "G:\Lab Practice\file.txt"
将路径参数放在引号中 - 例如
java com.your.application.Main "G:\Lab Practice\file.txt"
您尝试过使用引号吗?
赞:args[0] is : "G:\Lab Practice\file.txt"
try (BufferedReader b = new BufferedReader(new FileReader(args[0]))) {
System.out.println("Reading from file :" + args[0]);
String s = null;
while ((s = b.readLine()) != null) {
System.out.println(s);
}
} catch (ArrayIndexOutOfBoundsException a) {
System.out.println("No file specified, quitting !");
} catch (FileNotFoundException fe) {
System.out.println("File not found :" + args[0]);
} catch (IOException ie) {
System.out.println("Error reading file : " + ie.getMessage());
}
这里的 args[0] 是:G:\Lab Practice\file.txt
输出: 找不到文件 :G:\Lab
这是因为路径中有一个space。 我也试过用 args[0]+args[1] 替换 args[0] 但它没有用。 谁能帮我解决这个问题?
只需将参数放在引号中即可:
java Class "G:\Lab Practice\file.txt"
如果没有 space,它会将每个参数视为 args
数组中的单独参数 - 因此 G:\Lab
是 args[0]
而 Practice\file.txt
是 args[1]
在你的例子中。
来自docs:
This is because the space character separates command-line arguments. To have Drink, Hot, and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.
我假设你这样调用你的程序:
java -jar application.jar G:\Lab Practice\file.txt
这只是意味着您有两个参数 - G:\Lab
(在 args[0]
中)和 Practice\file.txt
(在 args[1]
中)。现在两者都没有任何空格。
您需要在调用中添加一些引号:
java -jar application.jar "G:\Lab Practice\file.txt"
将路径参数放在引号中 - 例如
java com.your.application.Main "G:\Lab Practice\file.txt"
您尝试过使用引号吗?
赞:args[0] is : "G:\Lab Practice\file.txt"