tags:

views:

122

answers:

3

Hi,

I have problem with Runtime.exec() in Java My code:

String lol = "/home/pc/example.txt";
String[] b = {"touch", lol}; 
try {  
    Runtime.getRuntime().exec(b);  
} catch(Exception ex) {  
    doSomething(ex);  
}

It's working good but when I trying changle variable "lol" files doesn't create in hard disk

for instance: String lol = x.getPath(); where getPath() returns String

What should I do ?

Thanks for your reply :)

+1  A: 

Simply look at the content of lol, when you called x.getPath(). I would guess it is not an absolute path and the file gets created, but not where you expect it to be.

It x is a Java.io.File us getCanonicalPath() for an absolute path.

ZeissS
Good point but if I print x.getPath() gets result equals "/home/pc/example.txt". It's should be OK. When I using Runtime.getRuntime().exec("touch /home/pc/example.txt") it's work fine, but when I trying using function it's doesen't work.
kunkanwan
A: 

You are probably using a java.io.File
In that case getPath() doesn't return the absolute path. For example:

System.out.println(System.getProperty("user.dir")); // Prints "/home/pc/"
// This means that all files with an relative path will be located in "/home/pc/"
File file = new File("example.txt");
// Now the file, we are pointing to is: "/home/pc/example.txt"
System.out.println(file.getPath()); // Prints "example.txt"
System.out.println(file.getAbsolutePath()); // Prints "/home/pc/example.txt"

So, conclusion: use java.io.File.getAbsolutePath().

Tip: there also exists a java.io.File.getAbsoluteFile() method. This will return the absolute path when calling getPath().


I just read your comment to the other answer:

I think you did:

String[] cmd = {"touch /home/pc/example.txt"};
Runtime.getRuntime().exec(cmd);

This won't work, because the os searches for an application called "touch /home/pc/example.txt".
Now, you are thinking "WTF? Why?"
Because the method Runtime.getRuntime().exec(String cmd); splits your string up on the spaces. And Runtime.getRuntime().exec(String[] cmdarray); doesn't split it up. So, you have to do it by yourself:

String[] cmd = {"touch", "/home/pc/example.txt"};
Runtime.getRuntime().exec(cmd);
Martijn Courteaux
A: 

If the code works when you set the string to the literal "/home/pc/example.txt", and x.getPath also returns the same value, then it MUST work - it's as simple as that. Which means that x.getPath() is actually returning something else. Maybe there's whitespace in the string? Try comparing the strings directly:

if (!"/home/pc/example.txt".equals(x.getPath())) throw new RuntimeException();
Mike Baranczak