2

我正在使用 xjc 从 xsd 生成类。生成必须发生在 java 代码中。现在我已经这样做了:

Process child = Runtime.getRuntime().exec(command);
        try {
            System.out.println("waiting...");
            child.waitFor();
            System.out.println("waiting ended..");
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }

上述程序的输出是:

waiting...

我必须在生成这些类后使用它们。这里的问题是子进程永远不会退出并且控制永远不会回到java程序!
有没有办法做到这一点getRuntime().exec()

4

2 回答 2

4

您实际上可以在命令行工具后面使用驱动程序类 ( com.sun.tools.xjc.Driver )。这对我有用:

import com.sun.tools.xjc.BadCommandLineException;
import com.sun.tools.xjc.Driver;
import com.sun.tools.xjc.XJCListener;
import org.xml.sax.SAXParseException;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Generator {

    public static void main(String[] args) throws BadCommandLineException, IOException {
        final String targetDir = "jaxb-files";
        Path path = Paths.get(targetDir);
        if(!Files.exists(path)) {
            Files.createDirectories(path);
        }
        Driver.run(new String[]{"-d", targetDir,
                "D:\\dev\\onepoint\\tui\\java\\xsdjsonschema\\src\\main\\xsd\\test.xsd"}, new XJCListener() {

            @Override
            public void error(SAXParseException e) {
                printError(e, "ERROR");
            }

            @Override
            public void fatalError(SAXParseException e) {
                printError(e, "FATAL");
            }

            @Override
            public void warning(SAXParseException e) {
                printError(e, "WARN");
            }

            @Override
            public void info(SAXParseException e) {
                printError(e, "INFO");
            }

            private void printError(SAXParseException e, String level) {
                System.err.printf("%s: SAX Parse exception", level);
                e.printStackTrace();
            }
        });
    }
}
于 2017-01-19T16:57:48.977 回答
1

尝试这个

Process child = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(  
                                new InputStreamReader(child.getInputStream()));  
            String line = null;  
            while ((line = in.readLine()) != null) {  
                System.out.println(line);  
            }  
于 2013-06-26T05:50:37.950 回答