[英]CMD.exe command in java not terminating
I'm trying to use cmd.exe to search for a file in a specific directory and then display the path in a java program and write it to a file. 我正在尝试使用cmd.exe搜索特定目录中的文件,然后在java程序中显示该路径并将其写入文件。 The problem is that the process never terminates. 问题是该过程永远不会终止。
Here is my code: 这是我的代码:
String[] str = new String[] { "cmd.exe ", "cd c:\\",
" dir /b /s documents", "2>&1" };
Runtime rt = Runtime.getRuntime();
try{
Process p = rt.exec(str);
InputStream is =p.getInputStream();
InputStreamReader in = new InputStreamReader(is);
StringBuffer sb = new StringBuffer();
BufferedReader buff = new BufferedReader(in);
String line = buff.readLine();
while( line != null )
{
sb.append(line + "\n");
line = buff.readLine();
}
System.out.println( sb );
File f = new File("test.txt");
FileOutputStream fos = new FileOutputStream(f);
fos.write(sb.toString().getBytes());
fos.close();
}catch( Exception ex )
{
ex.printStackTrace();
}
Runtime.exec
doesn't work that way. Runtime.exec
无法正常工作。 You can't pass multiple commands like that to cmd.exe. 您不能将这样的多个命令传递给cmd.exe。
Runtime.exec
allows you to execute a single process with a list of arguments. Runtime.exec
允许您使用参数列表执行单个进程。 It does not provide any "shell" operations (like 2>&1
for instance). 它不提供任何“shell”操作(例如2>&1
)。 You must do that sort of IO redirection yourself using the Input/Output streams. 您必须使用输入/输出流自己进行那种IO重定向。
It's similar to calling another program's main
function. 它类似于调用另一个程序的main
功能。
You could try `Runtime.exec( new String[] { "cmd.exe", "/c", "dir", "C:\\\\" } ); 您可以尝试`Runtime.exec(new String [] {“cmd.exe”,“/ c”,“dir”,“C:\\\\”});
But realistically, if you want file listings, you're much better off using the facilities in the java.io.File
class, which won't depend on operating system specific features. 但实际上,如果你想要文件列表,你最好使用java.io.File
类中的工具,这不依赖于操作系统特定的功能。
You must use the start command in addition to the cmd.exe process with the /C or /K switch BEFORE the start command. 在启动命令之前,必须使用带有/ C或/ K开关的cmd.exe进程之外的start命令。 Example: to convert the Windows's command interpreter in a bash console (from the mingw prroject) you must invoke the exec method of the Runtime class with the command "C:\\Windows\\System32\\cmd.exe /C start C:\\mingw\\msys\\1.0\\bin\\bash.exe" (I use an external command rather than an internal because it's more signifiant but you can use internal command like DIR and so on). 示例:要在bash控制台(来自mingw项目)中转换Windows的命令解释器,必须使用命令“C:\\ Windows \\ System32 \\ cmd.exe / C start C:\\ mingw \\”调用Runtime类的exec方法msys \\ 1.0 \\ bin \\ bash.exe“(我使用外部命令而不是内部命令,因为它更有意义,但您可以使用内部命令,如DIR等)。
why are not using Java to do directory traversal instead of calling external shell command? 为什么不使用Java来执行目录遍历而不是调用外部shell命令? It makes your code not portable! 它使你的代码不可移植!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.