i have a simle java method where i am trying to move files from one directory to another. Below is the code
there are no exceptions thrown in java but for some reason it sometimes give an exit value which indicates an abnormal termination, i.e exit value of 2. I cant figure out why.
any suggestions would be greatly appreciated.
However you should not be using the "mv" command since this is a platform specific solution.
Just use the File.renameTo(..) method.
- X 2
However if for some reason you really need to do this with Runtime.exec(), I recommend reading When Runtime.exec() won't. The article is over ten years old but still the best source I know of for this information; the only thing really missing is that it hasn't been updated to include ProcessBuilder, which would make the code a bit cleaner. However most of the key issues remain the same with ProcessBuilder as with Runtime.exec(). I think it's likely that the most useful advice for you will be to look at the error stream and see what it says. There's probably a message there that will give a clue about what the problem is.
"Bit" is the operative word; the differences with ProcessBulider are slight.
Mike Simmons wrote: . . . ProcessBuilder, . . . would make the code a bit cleaner. . . . .
Mike Simmons wrote:Even so, why not try using renameTo()? I suspect it will be considerably easier than what you're doing, and just as fast.
And also probably has the advantage that if there is something preventing the move, such as access permissions, you're more likely to get a useful error message.
One nice thing about ProcessBuilder is the ability to redirect the error stream to regular output. Doing this removes the need to process the two streams in separate threads, which is considerably simpler. This can be done with Runtime.exec() as well, by passing a redirect like "2>&1" to the operating system. But that's OS-dependent, and less understandable to most readers.
Rob Spoor wrote:Depends on what you find useful. File.renameTo returns false if it fails, but it never tells you why it fails. That has been solved in Java 7 with the java.nio.file.Path class and its moveTo method. It throws an exception instead when it fails.
Ah, yes, I'd forgotten that. Just assumed it threw an exception without checking. Ignore what I said, then .