输出“dir”的结果Java 中的控制台
我想将“dir”命令的结果输出到java控制台。我已经在谷歌和这里查看过,但没有一个例子适合我,因此让我写下了这篇文章。
我的代码如下:
try
{
System.out.println("Thread started..");
String line = "";
String cmd = "dir";
Process child = Runtime.getRuntime().exec(cmd);
//Read output
BufferedReader dis = new BufferedReader( new InputStreamReader(child.getInputStream() ));
while ((line = dis.readLine()) != null)
{
System.out.println("Line: " + line);
}
dis.close();
}catch (IOException e){
}
我做错了什么?
任何帮助都会非常好。
提前致谢,
达里尔
I want to output the result of the "dir" command to the java console. I have already looked on Google and here, but none of the examples work for me, thus making me rite this post.
My code is as follows:
try
{
System.out.println("Thread started..");
String line = "";
String cmd = "dir";
Process child = Runtime.getRuntime().exec(cmd);
//Read output
BufferedReader dis = new BufferedReader( new InputStreamReader(child.getInputStream() ));
while ((line = dis.readLine()) != null)
{
System.out.println("Line: " + line);
}
dis.close();
}catch (IOException e){
}
What am I doing wrong?
Any help would be very nice.
Thanks in advance,
Darryl
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
String cmd = "cmd dir";
。e.printStackTrace());
会告诉您我在 (1) 中写的内容。 永远不要忽略异常!String cmd = "cmd dir";
.e.printStackTrace());
in the catch block would tell you what I wrote in (1). Never ignore exceptions!最好的方法是使用 commons exec http://commons.apache.org/exec/
这有那些奇怪的事情确实会让你感到烦恼,比如如果你没有清除它的输出流,整个进程就会阻塞,在命令中转义引号,等等。
下面是一个可以在 Windows 中成功运行 del 命令的方法。请注意 cmd 的使用,因为 del 不是独立的可执行文件:
The best way is to use commons exec http://commons.apache.org/exec/
This has things that catch quirks that can really drive you up the wall, such as the whole process blocking if you didn't clear its output stream, escaping quotes in commands, etc.
Here is a method that will run the del command in windows successfully. Note the use of cmd since del is not a standalone executable:
这是一个更全面的示例,说明了操作系统版本和错误条件(如上面 MByD 所述)
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
请记住,使用“exec ”意味着您的应用程序不再是跨平台的,并且失去了 Java 的主要优势之一。
更好的方法是使用 java.io 包。
http://download.oracle.com/javase/tutorial/essential/io /dirs.html
Here is a more thorough example that accounts for OS versions and error conditions ( as stated by MByD above)
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
Remember that using "exec" means that your application is no longer cross-platform and loses one of the main advantages of Java.
A better approach is to use java.io package.
http://download.oracle.com/javase/tutorial/essential/io/dirs.html
你也可以在 java 6 中做类似的事情:
You can also do something like that in java 6 :