我正在构建一个工具,它应该通过 Windows 命令提示符从格式 A 转换为格式 B。我编写了类似交互模式的程序。 cmd 等待输入命令并处理它们。 现在,如果我调用该程序,我想传递一些参数。 args 将被传递,但程序不会自行执行命令。
我像这样传递参数:
java -jar test.jar -interactive//激活交互模式,不会出现任何问题
像这样(传递源文件、保存转换文件的目标位置、目标格式以及转换过程中使用的配置文件):
java -jar test.jar C:\Users\User\Desktop\test.json C:\Users\User\Desktop .xes C:\Users\User\Desktop\test.properties
到目前为止的代码:
public static void main(final String[] args) throws IOException, InterruptedException {
if (args[0].equals("-interactive")) {
testing test = new testing();
test.startCMD();
} else if (args[0] != null && args[1] != null && args[2] != null && args[3] != null) {
final testing test = new testing();
test.startCMD();
//the following construct doesn't work unfortunatelly
worker = Executors.newSingleThreadScheduledExecutor();
Runnable task = new Runnable() {
@Override
public void run() {
test.setSourceFile(args[0]);
test.setTargetPath(args[1]);
test.setTargetFormat(args[2]);
test.setConfigFilePath(args[3]);
System.out.println("Invoking the conversion routine now ...");
ConverterControl control = new ConverterControl();
control.link(sourceFilePath, targetPath, configFilePath, targetFormat, fileConfig);
}
};
worker.schedule(task, 5, TimeUnit.SECONDS);
}
}
public void startCMD() throws IOException, InterruptedException {
String[] command
= {
"cmd",};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Welcome to the Windows command line prompt." + System.lineSeparator());
System.out.println("Please type \"help\" to receive a list of commands available in this environment.");
//String s = in.readLine();
String input;
while ((input = in.readLine()) != null) {
//process the inputs
}
您在 main 方法中看到的不同 setter
只是将传递的信息设置为在类顶部声明的变量。然后,这些变量应该传递给 ConverterControl
,它的 link()
方法中有整个转换例程。
如果我在执行 startCMD()
命令后传递了 4 个参数(请参阅顶部的程序的第二次调用),程序就会停止。
有人知道如何调用这些方法并自动启动ConverterControl
吗?
最佳答案
您可能会陷入 startCmd()
末尾的 while 循环,并且您的程序将不再继续。
关于java - 自动执行带有args的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27965969/