I am calling the below command using java
This is the java initialization
String fileName="C:\\temp\\A a.txt";
String sCmd = "cmd /c start \"\" \"" + fileName + "\"";
This is what I get when I print sCmd
cmd /c start '" 'C:\temp\A a.txt'
This is how I run the command
Runtime.getRuntime().exec(sCmd);
The file name contains multiple spaces and when I run this command from Java its throwing an error because its not recognizing the multiple spaces.It works when no space or one space is there?How to handle files with multiple spaces through windows command
Sample java program
import java.io.File;
import java.io.IOException;
public class A
{
public static void main(String[] args)
{
String fileName = "C:\\temp\\a dfdfd f.txt";
File file = new File(fileName);
String sCmd = "cmd /c start \"\" \"" + file.getAbsolutePath() + "\"";
System.out.println("exec cmd=<" + sCmd + ">");
try
{
Runtime.getRuntime().exec(sCmd);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This gives me error when from windows side when I run the java code.
This is the java output
exec cmd=<cmd /c start "" "C:\temp\a dfdfd f.txt">
and I am running in Windows XP further this is not opening any file leave aside one with spaces.
Solution:
import java.io.File;
import java.io.IOException;
public class A
{
public static void main(String[] args)
{
// String fileName = "C:\\temp\\a.txt";
String fileName = "C:\\temp\\a dfdfd f.txt";
File file = new File(fileName);
String sCmd = "cmd /c start \"\" \"" + file.getAbsolutePath() + "\"";
System.out.println("exec cmd=<" + sCmd + ">");
try
{
Runtime.getRuntime().exec(sCmd.split(" "));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
cmd /c start "C:\\temp\\A a.txt"
works from the command line. You would need to escape the double quotes in the above command with a back slash if this command is called via Java's Runtime.getRuntime().exec(...)
I'm not exactly sure what you're doing but if it's simply cmd /c start <filename>
then this has too quotes.
String sCmd = "cmd /c start \"\" \"" + fileName + "\"";
It should be
String sCmd = "cmd /c start \"" + fileName + "\"";
As an aside:
This is what I get when I print sCmd
cmd /c start '" 'C:\temp\A a.txt'
I don't see how you could get single quotes in the output when they aren't present in your string!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.