简体   繁体   English

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

[英]Outputting result of “dir” to console in Java

I want to output the result of the "dir" command to the java console. 我想将“ dir”命令的结果输出到Java控制台。 I have already looked on Google and here, but none of the examples work for me, thus making me rite this post. 我已经在Google和此处查看过,但是这些示例都不适合我,因此让我感动了这篇文章。

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 达里尔

  1. You cannot run "dir" as a process, you need to change it to String cmd = "cmd dir"; 您不能将“ dir”作为进程运行,需要将其更改为String cmd = "cmd dir"; .
  2. You don't handle the exception at all. 您根本不处理异常。 adding the line e.printStackTrace()); 添加行e.printStackTrace()); in the catch block would tell you what I wrote in (1). 在catch块中会告诉您我在(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. 这可能会导致您的程序挂起,处理错误流并使用不同的流并行读取两个流(错误和输入)。

The best way is to use commons exec http://commons.apache.org/exec/ 最好的方法是使用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. 这是一种将在Windows中成功运行del命令的方法。 Note the use of cmd since del is not a standalone executable: 请注意使用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);
}

You can also do something like that in java 6 : 您也可以在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());
        }
    }
}
  • a) What is the java console? a)什么是Java控制台?
  • 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. b)您应该使用javas File.listFiles()代替Runtime.exec,后者不是可移植的,并且需要进行名称拆分-对于包含空格,空格,换行符等的文件名,这很困难。
  • c) Whats wrong with your code? c)您的代码有什么问题?
  • d) Why don't you do anything in the case of Exception? d)如果发生异常,为什么不采取任何措施?

Here is a more thorough example that accounts for OS versions and error conditions ( as stated by MByD above) 这是一个更全面的示例,说明了操作系统版本和错误情况(如上面的MByD所述)

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4 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. 请记住,使用“ exec”意味着您的应用程序不再跨平台,并且失去了Java的主要优势之一。

A better approach is to use java.io package. 更好的方法是使用java.io包。

http://download.oracle.com/javase/tutorial/essential/io/dirs.html http://download.oracle.com/javase/tutorial/essential/io/dirs.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM