2012-07-25 37 views
1

我从Java运行一个命令行命令:写作命令行输出到文件在Java

ping localhost > output.txt 

的命令是通过Java发送这样的:

Process pr = rt.exec(command); 

出于某种原因该文件没有创建,但是当我从 命令行本身运行此命令时,该文件确实创建并且输出在该文件中。

为什么java命令不创建文件?

+2

检查[此篇](http://stackoverflow.com/questions/3643939/java-process-with-input-output-stream) – fvu 2012-07-25 12:48:08

回答

4

因为您没有将它指向文件。

在命令行中,您已请求将其重定向到文件。您必须通过Process对象(对应于实际流程的输出流)提供的InputStream在Java中执行相同的操作。

下面是如何从过程中获得输出。

InputStream in = new BufferedInputStream(pr.getInputStream()); 

您可以从此读取直到EOF,并将输出写入文件。如果您不希望此线程阻塞,请从另一个线程读取和写入。

InputStream in = new BufferedInputStream(pr.getInputStream()); 
OutputStream out = new BufferedOutputStream(new FileOutputStream("output.txt")); 

int cnt; 
byte[] buffer = new byte[1024]; 
while ((cnt = in.read(buffer)) != -1) { 
    out.write(buffer, 0, cnt); 
} 
1

我要保持它的简单,您使用的是Windows,请尝试:

Process pr = rt.exec("cmd /c \"ping localhost > output.txt\""); 
2

成功地从Java程序,执行该命令后,您需要读取输出,然后将输出转移到文件。

例如:

Process p = Runtime.getRuntime().exec("Your_Command"); 

    InputStream i = p.getInputStream(); 

    InputStreamReader isr = new InputStreamReader(i); 

    BufferedReader br = new BufferedReader(isr); 


    File f = new File("d:\\my.txt"); 

    FileWriter fw = new FileWriter(f);   // for appending use (f,true) 

    BufferedWriter bw = new BufferedWriter(fw); 

    while((br.readLine())!=null){ 


     bw.write(br.readLine());   // You can also use append. 
    }