I would like to know how to use linux MV command from java. I have tried various code but it didnt worked for me. can u let me know how can i move a file from one directory to another directory in linux operating system from java. My question was How to use linux MV command from java not how to move a file in java.
-
check with stackoverflow.com/questions/12970741/… to understand how to execute cmd in javasundar– sundar2013-02-07 05:47:32 +00:00Commented Feb 7, 2013 at 5:47
-
String[] command = {"sh","-c", "/home/web/abc/"+Filename+" /home/web/abc/"}; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(command); int exitVal = proc.waitFor(); System.out.println("Process exitValue: " + exitVal);Shaikh Azhar Alam– Shaikh Azhar Alam2013-02-07 05:50:07 +00:00Commented Feb 7, 2013 at 5:50
-
@theJollySin- I thought that when a solution is available to use command available in operating system then why shld we code the same thing. its of no use. My question was to move a file using mv command in linux but not how to move a file in java . Anyways thank you. I got my solution.Shaikh Azhar Alam– Shaikh Azhar Alam2013-02-07 06:22:05 +00:00Commented Feb 7, 2013 at 6:22
Add a comment
|
3 Answers
If you are running a Java app on a *nix system, and assuming your app has permission to execute the mv command try the following code
String[] shCommand = {"/bin/sh", "-c", "mv somefile newfile"};
// creates a process to run the command in
Runtime rt = Runtime.getRuntime();
Process prcs = null;
try
{
// run the command
prcs = rt.exec(shCommand);
}
catch (Exception e)
{
console.err("Execute Command Error:");
e.printStackTrace();
}
You need to create a Runtime to interface with environment your Java app is running (*nix in this case) and Process to run a process in the environment
EDIT: you may not need the Process part, as I usually use it to have my app wait for command to finish executing or to get the exitcode, so if you don't need those you may omit the Process part