Java - Runtime.getRuntime().exec() what's going on?
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 w开发者_如何学Pythonhen 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 :)
Here is the solution to your problem . I faced a similar problem and this worked for me by specefying the output directory, it should execute the output of your files in that working directory.
ProcessBuilder proc = new ProcessBuilder("<YOUR_DIRECTORY_PATH>" + "abc.exe"); // <your executable path>
proc.redirectOutput(ProcessBuilder.Redirect.INHERIT); //
proc.directory(fi); // fi = your output directory
proc.start();
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);
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.
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();
like write code for real path
String path = request.getSession().getServletContext().getRealPath("/");
here u can get real path ..........
精彩评论