我正在嘗試從 java 運行 windows CLI 命令。我在決議結果時遇到了一個問題,但只有在從 cli 將代碼作為可運行 jar 運行時,在 eclipse 中它運行良好
private static List<String> runWindowsCommandAsRuntime(String command) {
List<String> out = new ArrayList<String>();
String[] comm = {
"C:\\Windows\\System32\\cmd.exe",
"/S",
"/K",
"\"" command "\"",
"&",
"exit" //devo uscire o il processo CMD resta appeso e non esce l'output
};
String dbg = "";
for(String s : comm)
dbg = s " ";
System.out.println("COMMAND: " dbg);
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(comm);
//get the output
out.addAll(
new BufferedReader(new InputStreamReader(p.getInputStream()))
.lines().toList() //the exception is thrown here
);
int exitVal = p.exitValue();
System.out.println("Exited with error code " exitVal);
p.destroy();
} catch (Exception ex) {
Utility.logException("Utility(SystemWindows)", ex);
return null;
}
return out;
}
// sample call: runWindowsCommandAsRuntime("WMIC OS Get Caption,Version");
當我通過 eclipse 運行程式時它作業正常,當我從 cli ( java -jar my_program.jar)呼叫它時它啟動然后拋出這個
我檢查了 java 版本,并且都在 eclipse 和 cli java 11 上
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:61)
Caused by: java.lang.NoSuchMethodError: java.util.stream.Stream.toList()Ljava/util/List;
uj5u.com熱心網友回復:
說明:您試圖在流上呼叫 .toList(),而流沒有 .toList() 方法(在 Java < 16 中),因此您必須使用收集器。
簡短的回答:如果你想用 Java < 16 運行你的程式,你可以使用.collect(Collectors.toList())而不是.toList(),或者你可以.toList()在流上使用(就像你現在正在做的那樣)但至少用 Java 16 運行它。
如果你想用 16 歲以上的 Java 運行它,你的整個代碼應該是這樣的:
private static List<String> runWindowsCommandAsRuntime(String command) {
List<String> out = new ArrayList<String>();
String[] comm = {
"C:\\Windows\\System32\\cmd.exe",
"/S",
"/K",
"\"" command "\"",
"&",
"exit" //devo uscire o il processo CMD resta appeso e non esce l'output
};
String dbg = "";
for (String s : comm)
dbg = s " ";
System.out.println("COMMAND: " dbg);
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(comm);
//get the output
out.addAll(
new BufferedReader(new InputStreamReader(p.getInputStream()))
.lines().collect(Collectors.toList()) //the exception is thrown here
);
int exitVal = p.exitValue();
System.out.println("Exited with error code " exitVal);
p.destroy();
} catch (Exception ex) {
return null;
}
return out;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/409885.html
標籤:
上一篇:Kivyscreenmanager當前螢屏沒有切換(至少在視覺上沒有)。使用kivymd
下一篇:單贏表單視窗上的流程
