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);