“dir”的输出结果以Java控制 [英] Outputting result of "dir" to console in Java

查看:121
本文介绍了“dir”的输出结果以Java控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将dir命令的结果输出到java控制台。我已经在谷歌和这里看过,但没有一个例子适用于我,所以让我礼貌的这个帖子。

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.

我的代码如下:

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?

任何帮助都会很好。

提前感谢,

Darryl

推荐答案


  1. 你不能运行dir作为一个进程,您需要将其更改为 String cmd =cmd dir;

  2. 完全处理异常。在catch块中添加行 e.printStackTrace()); 会告诉你我在(1)中写的内容。 不要忽略异常!

  3. 您不处理错误流。这可能会导致您的程序挂起,处理错误流,并使用不同的流并行读取两个流(错误和输入)。

  1. You cannot run "dir" as a process, you need to change it to String cmd = "cmd dir";.
  2. You don't handle the exception at all. adding the line e.printStackTrace()); in the catch block would tell you what I wrote in (1). Never ignore exceptions!
  3. You don't handle error stream. This might cause your program to hang, handle error stream and read from both streams (error and input) in parallel using different streams.

这篇关于“dir”的输出结果以Java控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆