errorNoSuchMethodError: java.util.stream.Stream.toList()Ljav



我正在尝试从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");

当我在日食时运行程序时,它工作正常, 当我从 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;

解释: 您正在尝试在流上调用 .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;
}

最新更新