简体   繁体   English

运行一个简单的文本文件为 Java

[英]Run a simple text file as Java

I have a simple.txt file which has pure Java code inside it like我有一个 simple.txt 文件,里面有纯 Java 代码

   public class C {
      public static void main(String[] args ) {
        System.out.println("This is executed");
        }
    }

The file is named C.txt.该文件名为 C.txt。 Now I want to write Java code that will read the code in C.txt and will compile and run the read code as a pure Java file.现在我想编写 Java 代码,它将读取 C.txt 中的代码,并将读取的代码编译并运行为纯 Java 文件。 Note, I can easily rename C.txt to C.java and compile and run the code manually.注意,我可以轻松地将 C.txt 重命名为 C.java 并手动编译和运行代码。 However, this is not my intention.然而,这不是我的本意。 I want to read the.txt file as is and execute the code directly.我想按原样读取 .txt 文件并直接执行代码。 Is this possible somehow?这有可能吗?

You can use the javax.tools api form Java 6 to compile the code on the fly.您可以使用javax.tools api 形式 Java 6 即时编译代码。 However since your extension is illegal it will complain with a error: C.txt Class names are only accepted if annotation processing is explicitly requested .但是,由于您的扩展名是非法的,它会报错: C.txt Class 名称仅在明确请求注释处理时才被接受

To get around this (as mentioned in the comments) you must first load the code into a String and then execute it:要解决这个问题(如评论中所述),您必须首先将代码加载到 String 中,然后执行它:

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class MyCompiler2 {
    public static void main(String[] args) throws Exception {
        String program = "";
        try {
            BufferedReader in = new BufferedReader(new FileReader("C.txt"));
            String str;
            while ((str = in.readLine()) != null) {
                program += str;
            }
            in.close();
        } catch (IOException e) {
        }

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        Iterable<? extends JavaFileObject> fileObjects;
        fileObjects = getJavaSourceFromString(program);

        compiler.getTask(null, null, null, null, null, fileObjects).call();

        Class<?> clazz = Class.forName("C");
        Method m = clazz.getMethod("main", new Class[]{String[].class});
        Object[] _args = new Object[]{new String[0]};
        m.invoke(null, _args);
    }

    static Iterable<JavaSourceFromString> getJavaSourceFromString(String code) {
        final JavaSourceFromString jsfs;
        jsfs = new JavaSourceFromString("code", code);
        return new Iterable<JavaSourceFromString>() {
            public Iterator<JavaSourceFromString> iterator() {
                return new Iterator<JavaSourceFromString>() {
                    boolean isNext = true;

                    public boolean hasNext() {
                        return isNext;
                    }

                    public JavaSourceFromString next() {
                        if (!isNext)
                            throw new NoSuchElementException();
                        isNext = false;
                        return jsfs;
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }
}

class JavaSourceFromString extends SimpleJavaFileObject {
    final String code;

    JavaSourceFromString(String name, String code) {
        super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
        this.code = code;
    }

    public CharSequence getCharContent(boolean ignoreEncodingErrors) {
        return code;
    }
}

Notice how you need to explicitly provide the method and class name in order for reflection to execute your code.请注意您需要如何显式提供方法class名称,以便反射执行您的代码。

Check out this thread for how to start the compile from within Java...查看此线程以了解如何从 Java 中开始编译...

How to set the source for compilation by a CompilationTask 如何通过 CompilationTask 设置编译源

I think I'd start with BeanShell , which allows you to compile and execute Java source held in a string.我想我会从BeanShell开始,它允许您编译和执行保存在字符串中的 Java 源代码。

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

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