我正在构建一个工具,该工具应该通过Windows命令提示符从格式A转换为格式B。我编写了一些类似于交互模式的东西。cmd 等待输入命令并处理它们。现在我想通过一些参数,如果我调用程序。参数将被传递,但程序不会自行执行命令。
我像这样传递参数:
java -jar test.jar -interactive //activates the interactive mode, which does not make any problems
像这样(传递源文件、保存转换后文件的目标位置、目标格式,最后是转换期间使用的配置文件):
java -jar test.jar C:UsersUserDesktoptest.json C:UsersUserDesktop .xes C:UsersUserDesktoptest.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 循环中,并且你的程序永远不会继续下去。
如果你收到了命令行参数,为什么要调用startCMD()?
顺便说一句,看起来您可能也滥用了静态变量。
为了整理这一点,你的"测试"类应该实现 Runnable,你应该把对你的"test"对象的引用传递给你的 worker。
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();//Why is this call here?
test.setSourceFile(args[0]);
test.setTargetPath(args[1]);
test.setTargetFormat(args[2]);
test.setConfigFilePath(args[3]);
worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(test, 5, TimeUnit.SECONDS);
}
run() 方法的其余部分将简单地移到"测试"类中的 run() 方法中。
@Override
public void run() {
ConverterControl control = new ConverterControl();
control.link(sourceFilePath, targetPath, configFilePath, targetFormat, fileConfig);
}