-1

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.

Shaikh Azhar Alam
  • 173
  • 1
  • 3
  • 16
  • check with http://stackoverflow.com/questions/12970741/executing-linux-command-in-java to understand how to execute cmd in java – sundar Feb 07 '13 at 05: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 Feb 07 '13 at 05: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 Feb 07 '13 at 06:22

3 Answers3

2

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

jeffchong07
  • 552
  • 6
  • 13
0

System.getRuntime().exec("bash mv ....");

Replace with your actual command and execute

TheWhiteRabbit
  • 15,480
  • 4
  • 33
  • 57
0

This would work:

Runtime runtime = Runtime.getRuntime();
String[] runCommand = new String[3];
runCommand[0] = "sh";
runCommand[1] = "-c";
runCommand[2] = "mv a.txt b.txt";
Process process = runtime.exec(runCommand);
process.waitFor();
Tirthankar
  • 565
  • 1
  • 6
  • 10