Runtime exec() doesn't run commands when filename has spaces [duplicate]

流过昼夜 提交于 2019-12-20 02:58:22

问题


I am new to Java and trying to convert one of my project from C to Java in order to combine it with another Java program. I'm having difficulty to get correct result when I use Runtime.exec(). I have the following program segment and Java ignores to process the given command.

command1 = "mv output/tsk/dir1/metabolic\\ waste.txt output/converted/file16.txt";                                               
r2 = Runtime.getRuntime();
p2 = r2.exec(command1);
p2.waitFor();

The problem here is the filename "metabolic waste.txt". The same command work when there is no space. I know I have to use escape char for space and I do it. I'm working on Ubuntu btw.

I also tried using

String[] command1 = new String[] {"mv output/tsk/dir1/metabolic\ waste.txt", "output/converted/file16.txt";

but it didn't work.

p.s. the given code is just an example. I don't only use linux mv command. I also run some of the command line tools such as pdf2txt. I still have the same problem of running commands if there is any space in the filename.

SOLVED: I've solved my problem. It's ridiculous that I had to remove escape character and use string array. So, NO ESCAPE CHARACTER for space. The following code just worked for this example and for more general.

source_filepath = "output/tsk/dir1/metabolic waste.txt";
dest_filepath = "output/converted/file16.txt";
String[] str2= {"mv", source_filepath, dest_filepath};
r2 = Runtime.getRuntime().exec(str2);
p2.waitFor();

回答1:


You have to escape the escape, or enclose the path in quotes:

String[] command1 = new String[] {"mv output/tsk/dir1/metabolic\\ waste.txt", "output/converted/file16.txt"};
String[] command1 = new String[] {"mv \"output/tsk/dir1/metabolic waste.txt\"", "output/converted/file16.txt"};

You have to use \\ because java also uses \ as an escape character, so "\\" really just contains one \




回答2:


You can enclose the filename in double quotes as follows :

  String srcFile = "output/tsk/dir1/metabolic\\ waste.txt"
  command1 = "mv " + srcFile +" output/converted/file16.txt";                     


来源:https://stackoverflow.com/questions/23660096/runtime-exec-doesnt-run-commands-when-filename-has-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!