2010-09-23 77 views
2

如何使这个工作在Windows上,文件filename.txt没有被创建。运行时问题

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

显然,期望输出是一个 “FILENAME.TXT” 应被创建(C:\ Documents和Settings \用户名\ FILENAME.TXT)与内容 “名称”。


之所以能够用下面的代码来管理,即使该文件是 “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); 
     } 

或使用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); 
} 
+1

怎么不工作吗? – Bozho 2010-09-23 11:06:23

+0

它不起作用的方式? – 2010-09-23 11:06:45

+0

显然?你是从'C:\ Documents and Settings \ username \'文件夹直接运行它吗? – 2010-09-23 11:12:33

回答

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

(我会适应它cmd并呼应,如果我有一个窗口机在到达...随意编辑这个职位!)

+0

请记住,ProcessBuilder是在JDK 5中引入的。较早版本的JDK仍然需要'Runtime.exec(...)'。 – 2010-09-23 11:14:02

+0

无论您使用ProcessBuilder还是exec(),问题的根源(传递在错误位置分割的单个字符串)都保持不变。 – musiKk 2010-09-23 11:50:35

+0

我的实际需求是“cmd cleartool lsview> views.txt”,命令cleartool lsview的执行输出应该转到views.txt文件。这与正常的cmd提示符正常工作。但在我的java程序中,我喜欢实现这个 – srinannapa 2010-09-23 11:52:03

4

它应该与

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

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

背后的原因是,在您的版本中,命令在每个空格字符处被分割。因此,运行时所要做的是创建一个进程cmd并为其提供参数echo,name,>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/")); 
+0

平台相关的解决方案来达到同样的效果。 – aioobe 2010-09-23 11:09:17

+2

这是一个依赖于平台的问题:) – Bozho 2010-09-23 11:10:11

+0

是Bozho。我真的不明白这个意见。如果你执行某些事情(几乎?)总是依赖于平台。 – musiKk 2010-09-23 11:11:55