输出“dir”的结果Java 中的控制台

发布于 2024-11-03 10:34:09 字数 636 浏览 7 评论 0原文

我想将“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

醉城メ夜风 2024-11-10 10:34:09
  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.
乖不如嘢 2024-11-10 10:34:09

最好的方法是使用 commons exec http://commons.apache.org/exec/

这有那些奇怪的事情确实会让你感到烦恼,比如如果你没有清除它的输出流,整个进程就会阻塞,在命令中转义引号,等等。

下面是一个可以在 Windows 中成功运行 del 命令的方法。请注意 cmd 的使用,因为 del 不是独立的可执行文件:

private void deleteWithCmd(File toDelete) throws IOException {
    CommandLine cmdLine = new CommandLine("cmd.exe");
    cmdLine.addArgument("/C");
    cmdLine.addArgument("del");
    cmdLine.addArgument(toDelete.getAbsolutePath());
    DefaultExecutor executor = new DefaultExecutor();
    int exitValue = executor.execute(cmdLine);
}

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:

private void deleteWithCmd(File toDelete) throws IOException {
    CommandLine cmdLine = new CommandLine("cmd.exe");
    cmdLine.addArgument("/C");
    cmdLine.addArgument("del");
    cmdLine.addArgument(toDelete.getAbsolutePath());
    DefaultExecutor executor = new DefaultExecutor();
    int exitValue = executor.execute(cmdLine);
}
风吹短裙飘 2024-11-10 10:34:09
  • a) 什么是java控制台?
  • b) 您应该使用 javas File.listFiles () 而不是 Runtime.exec,后者不可移植,并且使得名称分割成为必要 - 对于包含空格、空格、换行符等的文件名来说是一件困难的事情。
  • c) 你的代码有什么问题吗?
  • d) 出现异常时为什么不采取任何措施?
  • a) What is the java console?
  • b) You should use javas File.listFiles () instead of Runtime.exec, which isn't portable, and makes Name splitting neccessary - a hard thing, for filenames which contain spaces, blanks, newlines and so on.
  • c) Whats wrong with your code?
  • d) Why don't you do anything in the case of Exception?
稳稳的幸福 2024-11-10 10:34:09

这是一个更全面的示例,说明了操作系统版本和错误条件(如上面 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

靑春怀旧 2024-11-10 10:34:09

你也可以在 java 6 中做类似的事情:

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

public class ListFilesFromRegExp {

    public static void main(String[] args) throws IOException {
        File dir = new File("files/");
        File[] files = dir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.matches("File[0-9].c");
            }
        });
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i].getAbsolutePath());
        }
    }
}

You can also do something like that in java 6 :

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

public class ListFilesFromRegExp {

    public static void main(String[] args) throws IOException {
        File dir = new File("files/");
        File[] files = dir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.matches("File[0-9].c");
            }
        });
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i].getAbsolutePath());
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文