简体   繁体   中英

Writing to a .java file in java and running the script

I'm currently trying to write a .java file in Java. I have some class Driver which calls my sub-class 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):

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. I run the script, look at Auto.java, and to my surprise, nothing's been written!

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?

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 . The current directory is the directory from which the java command is executed:

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

In the above example, the file will be written to /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. It's typically set by default by the IDE to the root of the project.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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