2013-02-07 87 views
-2

我想知道如何从java使用linux MV命令。我尝试了各种代码,但它没有为我工作。你可以让我知道如何将文件从一个目录移动到linux操作系统中的另一个目录。我的问题是如何使用从Java的Linux MV命令,而不是如何在Java中移动文件。Linux MV命令来自Java

+0

检查与http://stackoverflow.com/questions/12970741/executing-linux-command-in-java了解如何在Java执行CMD – sundar

+0

的String []命令= {” sh“,” - c“,”/ home/web/abc /“+文件名+”/ home/web/abc /“}; 运行时rt = Runtime.getRuntime(); Process proc = rt.exec(command); int exitVal = proc.waitFor(); System.out.println(“Process exitValue:”+ exitVal); –

+0

@ theJollySin-我认为当一个解决方案可以使用操作系统中可用的命令时,为什么我们编码的是相同的东西。它没用。我的问题是在Linux中使用mv命令移动文件,但不知道如何在java中移动文件。反正谢谢你。我有我的解决方案。 –

回答

1

如果您正在运行的* nix系统上的Java应用程序,并假设您的应用程序权限执行mv命令试试下面的代码

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

您需要创建一个运行环境与接口的Java应用程序正在运行(*在这种情况下尼克斯)和过程在环境中运行的过程

编辑:你可能不需要过程部分,因为我通常使用它来让我的应用程序等待命令完成执行或获取退出代码,所以如果你不需要那些,你可以省略过程部分

+0

谢谢你解决我的问题。 –

0

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

替换为您实际的命令并执行

0

这会工作:

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