如果我执行以下操作,我的应用程序将启动并加载文件: cmd
中的 myApp/file:c:\nospaces.asd
但如果我执行 myApp/file :c:\withspaces.asd
它不会工作,因为程序接收两个参数:myApp/file:c:\with
和 spaces.asd
.
我知道我可以执行 myApp "/file:c:\withspaces.asd"
并且它会像 cmd
那样工作。然而,这不是一个好的解决方案,因为如果我双击 .asd
文件(自定义扩展)(并选择使用我的应用程序启动),那么 main
将不会得到参数作为一行但作为两个参数。
如何解决此问题,以便我的 main
在双击文件时仅收到一个参数?
最佳答案
如果找不到文件,您可以将参数连接在一起。像这样的事情:
public static void main(String[] args) {
String fileName = joinArgumentsToValidFileName(args);
}
public static String joinArgumentsToValidFileName(String[] args) {
if(args.length == 0) {
return "";
}
String fileName = args[0];
int index = 1;
while(!new File(fileName).exists() && index < args.length) {
fileName += " " + args[index];
index++;
}
return fileName;
}
这假设第一个参数(或多个参数)必须是文件名。任何额外的参数都可以通过以某种方式记住偏移索引来评估(不包括在上面的代码中)。
但请注意:这不是向应用程序传递参数的标准行为,可能会导致困惑。因此,如果您找到了传递 ""
包装文件名参数的方法,请不要这样做!
关于java - 如何处理参数中的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172977/