java中FileReader中以空格作为命令行参数传递目录时出现异常
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
这是因为路径中有一个空间。 我也尝试过用args[0]+args[1]替换args[0],但没有效果。 有人能帮我弄清楚吗
# 1 楼答案
简单地用引号把论点引起来:
在没有空格的情况下,它将每个变量视为
args
数组中的独立参数,因此G:\Lab
是args[0]
,而Practice\file.txt
是args[1]
从docs开始:
# 2 楼答案
我想你是这样称呼你的程序的:
这仅仅意味着你有两个参数-
G:\Lab
(在args[0]
)和Practice\file.txt
(在args[1]
)。现在两者都没有任何空间你需要在通话中加上一些引号:
# 3 楼答案
你试过用引号吗
比如:
args[0] is : "G:\Lab Practice\file.txt"