Question

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();
Was it helpful?

Solution

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 \

OTHER TIPS

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";                     
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top