简体   繁体   English

用Java写入.java文件并运行脚本

[英]Writing to a .java file in java and running the script

I'm currently trying to write a .java file in Java. 我目前正在尝试用Java编写.java文件。 I have some class Driver which calls my sub-class Eval: 我有一些类驱动程序,它调用我的子类Eval:

public class Driver
{
    public static void main(String[] args)
    {
        Eval eval = new Eval();
        eval.evaluate("System.out.println(\"Hello!!! I'm an auto-generated .java file!);\");
    }
}

Here's my Eval class (stored in the same project): 这是我的Eval类(存储在同一项目中):

public class Eval
{
    public Eval()
    {

    }

    public void evaluate(String toEval)
    {
        PrintWriter writer = new PrintWriter("Auto.java", "UTF-8");
        writer.println("public class Auto");
        writer.println("{");
        writer.println("    public static void main(String[] args)");
        writer.println("    {");
        writer.println("        " + toEval;
        writer.println("    }");
        writer.println("}");
        writer.close();
    }
}

So, I manually create the class Auto.java in the same directory. 因此,我在同一目录中手动创建了类Auto.java。 I run the script, look at Auto.java, and to my surprise, nothing's been written! 我运行脚本,查看Auto.java,令我惊讶的是,什么都没写!

public Auto
{
}

(Which is how I had left it after manually creating it) (这是我手动创建后离开的方式)
Any suggestions would be appreciated. 任何建议,将不胜感激。
Thanks! 谢谢!

PS Furthermore (though the above bug takes priority over this question), how could I run this program from the class Eval? PS此外(尽管上述错误优先于此问题),如何从Eval类运行此程序?

try this : 尝试这个 :

 /**
 * @author Rustam
 */
public class Test {


    public static void main(String[] args) throws FileNotFoundException,
            UnsupportedEncodingException {

        Eval eval = new Eval();
        eval.evaluate("System.out.println(\"Hello!!! I'm an auto-generated .java file!\")");
        try {
            runProcess("javac Auto.java");
            runProcess("java Auto");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void runProcess(String command) throws Exception {
        Process pro = Runtime.getRuntime().exec(command);
        printLines(command + " stdout:", pro.getInputStream());
        printLines(command + " stderr:", pro.getErrorStream());
        pro.waitFor();
        System.out.println(command + " exitValue() " + pro.exitValue());
    }

    private static void printLines(String name, InputStream ins) throws Exception {
        String line = null;
        BufferedReader in = new BufferedReader(
                new InputStreamReader(ins));
        while ((line = in.readLine()) != null) {
            System.out.println(name + " " + line);
        }
    }
}

class Eval
{
    public Eval()
    {

    }

    public void evaluate(String toEval) throws FileNotFoundException, UnsupportedEncodingException
    {
        PrintWriter writer = new PrintWriter("Auto.java", "UTF-8");
        writer.println("public class Auto");
        writer.println("{");
        writer.println("    public static void main(String[] args)");
        writer.println("    {");
        writer.println("        " + toEval + ";");
        writer.println("    }");
        writer.println("}");
        writer.close();
        System.out.println("Auto.java created..");
    }
}

output : 输出:

Auto.java created..
javac Auto.java exitValue() 0
java Auto stdout: Hello!!! I'm an auto-generated .java file!
java Auto exitValue() 0

You're probably not looking at the right place. 您可能没有找到正确的地方。 Your code writes in a files Auto.java of the current directory . 您的代码将写入当前目录的文件Auto.java The current directory is the directory from which the java command is executed: 当前目录是执行Java命令的目录:

> pwd
> /foo/bar/baz
>
> java com.mycompany.Driver

In the above example, the file will be written to /foo/bar/baz/Auto.java . 在上面的示例中,该文件将被写入/foo/bar/baz/Auto.java

If you're running from an IDE, then the "Run configuration" in your IDE should let you know (and change) the current directory. 如果从IDE运行,则IDE中的“运行配置”应该让您知道(并更改)当前目录。 It's typically set by default by the IDE to the root of the project. 通常,IDE默认将其设置为项目的根目录。

You really should add some exception handling: 您确实应该添加一些异常处理:

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

public class Driver
{
    public static void main(String[] args) throws FileNotFoundException,  UnsupportedEncodingException
    {
        Eval eval = new Eval();
        eval.evaluate("System.out.println(\"Hello!!! I'm an auto-generated .java file!);\");");

       //here we create an instance of the class (which will be created with code above) Auto
       Auto auto = new Auto();
    }
}

Then you also need to add some exception handling in your main class: 然后,您还需要在主类中添加一些异常处理:

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
public class Eval
{
    public void evaluate(String toEval) throws FileNotFoundException, UnsupportedEncodingException
    {
        PrintWriter writer = new PrintWriter("Auto.java", "UTF-8");
        writer.println("public class Auto");
        writer.println("{");
        writer.println("    Auto(){"); //You don't need another public static... just a constructor that prints the message
        writer.println("        " + toEval);
        writer.println("    }");
        writer.println("}");
        writer.close();
    }
}

Now I've tested this above and it works, so make sure your looking in the correct directory and make sure the file Auto is in the correct place (you may need to specify the path) ie: 现在,我已经在上面进行了测试,并且可以正常工作,因此请确保您在正确的目录中查找,并确保文件Auto位于正确的位置(您可能需要指定路径),即:

PrintWriter writer = new PrintWriter("C:/Users/You/Desktop/..../test.txt", "UTF-8");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM