运行时问题

时间:2010-09-23 11:04:26

标签: java runtime.exec

如何在Windows上完成此工作,文件filename.txt尚未创建。

Process p = Runtime.getRuntime().exec("cmd echo name > filename.txt");

显然,预期的输出是“filename.txt”应该创建(C:\ Documents and Settings \ username \ filename.txt),内容为“name”。


能够使用以下代码进行管理,即使文件是“filename.txt”没有使用processBuilder创建

       Runtime runtime = Runtime.getRuntime();
       Process process = runtime.exec("cmd /c cleartool lsview");
       // Directly to file

//Process p = Runtime.getRuntime().exec( 
//              new String[] { "cmd", "/c", "cleartool lsview > filename.txt" },null, new File("C:/Documents and Settings/username/")); 

       InputStream is = process.getInputStream();
       InputStreamReader isr = new InputStreamReader(is);
       BufferedReader br = new BufferedReader(isr);
       String line;

       System.out.printf("Output of running %s is:", 
           Arrays.toString(args));

       while ((line = br.readLine()) != null) {
         System.out.println(line);
       }

OR,使用ProceessBuilder,

Process process = new ProcessBuilder( "cmd", "/c", "cleartool lsview" ).start();
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));

System.out.printf("Output of running %s is:", Arrays.toString(args));

String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

2 个答案:

答案 0 :(得分:6)

您实际上应该使用ProcessBuilder而不是Runtime.exec(请参阅the docs)。

ProcessBuilder pb = new ProcessBuilder("your_command", "arg1", "arg2");
pb.directory(new File("C:/Documents and Settings/username/"));

OutputStream out = new FileOutputStream("filename.txt");
InputStream in = pb.start().getInputStream();

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
    out.write(buf, 0, len);

out.close();

(如果我有一台可以触及的Windows机器,我会将它改编成cmd并回显...随意编辑这篇文章!)

答案 1 :(得分:4)

它应该与

一起使用
Process p = Runtime.getRuntime().exec(
    new String[] { "cmd", "/c", "echo name > filename.txt" });

我目前没有运行Windows,所以不幸的是我无法测试它。

这背后的原因是在您的版本中,命令会在每个空格字符处被分割。因此,运行时所做的是创建一个流程cmd,并将参数echoname>filename.txt提供给它,这是没有意义的。命令echo name > filename.txtcmd进程的单个参数,因此您必须手动提供具有不同参数的数组。

如果要确保在特定文件夹中创建文件,则必须提供exec()的工作目录,该目录仅适用于三个参数版本:

Process p = Runtime.getRuntime().exec(
    new String[] { "cmd", "/c", "echo name > filename.txt" },
    null, new File("C:/Documents and Settings/username/"));