2010-08-26 165 views
4
import java.io.*; 

public class Auto { 

    /** 
    * @param args 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException { 

     try { 
      Runtime.getRuntime().exec("javac C:/HelloWorld.java"); 
      Runtime.getRuntime().exec("java C:/HelloWorld > C:/out.txt"); 
      System.out.println("END"); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

该方案是能够编译“HelloWorld.java”的文件,但不执行它(的HelloWorld)。 任何人都可以请建议我如何使它工作? 在此先感谢! :) 此外,如果输出可能能够在另一个文本文件中说'output.txt'。编译和执行使用Java代码运行#EXEC()

+1

您不执行.java文件。试试'java c:/ HelloWorld'。 – 2010-08-26 17:31:40

+2

它不是错我感兴趣的是,我已经纠正,但通过mistake.Sorry贴在旧的错误代码:) – ivorykoder 2010-08-26 17:37:32

+0

请告诉我如何执行程序 – cafebabe1991 2013-09-15 09:33:04

回答

4

当您运行java程序,您必须在你的项目的根目录,然后运行java package.to.ClassWhichContainsMainMethod

Runtime.getRuntime().exec()会给你一个Process它包含一个OutputStreamInpuStream执行的应用。

您可以将InputStream内容重定向到您的日志文件。

在你的情况我会使用此exec:public Process exec(String command, String[] envp, File dir)这样的:

exec("java HelloWorld", null, new File("C:/")); 

为了从InputStream数据复制到文件(被盗this post代码):

public runningMethod(){ 
    Process p = exec("java HelloWorld", null, new File("C:/")); 
    pipe(p.getInputStream(), new FileOutputStream("C:/test.txt")); 
} 

public void pipe(InputStream in, OutputStream out) { 
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 
    int writtenBytes; 
    while((writtenBytes = in.read(buf)) >= 0) { 
     out.write(buf, 0, writtenBytes); 
    } 
} 
+0

Andreas_D嗨 我尝试这样做: - 调用Runtime.getRuntime ().exec(“java HelloWorld”,null,new File(“C:/”)); 但仍然无法获取out.txt文件中的输出。 我不知道如何使用getInputStream和getOutputStreams。 可以请你告诉我如何获得out.txt文件中的输出? – ivorykoder 2010-08-26 19:02:36

+0

我更新了答案。 – 2010-08-26 19:21:34

0

您不要在java中执行“.java”。你执行一个类文件。因此更改第二行:

Runtime.getRuntime().exec("cd c:\;java HelloWorld > C:/out.txt"); 

至于输出,而不是重定向到一个文件,你可能需要使用InputStream的:

InputStream is = Runtime.getRuntime().exec("cd c:\;java HelloWorld").getInputStream(); 
3

3分。

  1. JavaCompiler在Java 1.6中引入,允许从Java代码中直接编译Java源代码。
  2. ProcessBuilder(1.5+)是启动Process的更简单/更可靠的方法。
  3. 要处理任何过程,请确保您阅读并实施了When Runtime.exec() won't的所有要点。