简体   繁体   English

命令行参数中的空格

[英]Spaces in Command Line Arguments

I am doing an assignment for university and I have a quick question regarding command line arguments and spaces.我正在为大学做作业,我有一个关于命令行参数和空格的快速问题。

I have to find an image file which will be given to us in the command line.我必须找到一个将在命令行中提供给我们的图像文件。 I am trying to run my program but because my file location has spaces in the folder names, java assumes that there is more than one argument.我正在尝试运行我的程序,但是因为我的文件位置在文件夹名称中有空格,所以 java 假设有多个参数。

Therefore when I assign args[0] to the String it stops half way through because of the spaces.因此,当我将args[0]分配给String ,由于空格,它会在中途停止。

Is there a way to just take everything from the command line and assign it to a String ?有没有办法从命令行中获取所有内容并将其分配给String

Thanks in advance :)提前致谢 :)

Just use quotes:只需使用引号:

java -jar MyThing.jar "My File Name with loads of spaces.jpg"

Quick demo:快速演示:

public static void main(final String[] args) throws Exception {   
    Stream.of(args).forEach(System.out::println);
}

Output:输出:

java -jar MyThing.jar My File Name with loads of spaces.jpg
My
File
Name
with
loads
of
spaces.jpg

java -jar MyThing.jar "My File Name with loads of spaces.jpg"
My File Name with loads of spaces.jpg

The system interprets the space character as a separator for command line arguments.系统将空格字符解释为命令行参数的分隔符。 If you want the argument with spaces you would join them with double quotes.如果你想要带有空格的参数,你可以用双引号将它们连接起来。

% java test.class "Java is escaped"
Java is escaped

If you select one or more files in File Explorer and run an app from RMB the arguments to app should be the files selected.如果您在文件资源管理器中选择一个或多个文件并从 RMB 运行应用程序,则应用程序的参数应为所选文件。 But if the folder in question contains spaces, you're stuck!但是如果有问题的文件夹包含空格,你就被卡住了! No way to add double quotes!没办法加双引号! Microsoft bug?微软漏洞?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM