-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.

3
  • check with stackoverflow.com/questions/12970741/… to understand how to execute cmd in java Commented 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); Commented 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. Commented Feb 7, 2013 at 6:22

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Replace with your actual command and execute

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.