繁体   English   中英

如何在Java中结束输入流

[英]How to end the input stream in java

我正在尝试使用input.close()关闭inputstream,但是我无法这样做。

              try {

        String line;
        Set<String> folderList = new HashSet<>();

        Process p = Runtime.getRuntime()
                .exec(new String[] { "cmd", "/K", "dir \"c:\\Program Files\\apache-tomcat-*\" /s" });

        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = input.readLine().trim()) != null) {
            if (line.contains("<DIR>")) {

                String folder = line.substring(line.indexOf("<DIR>") + "<DIR>".length()).trim();
                // System.out.println("c:\\Program Files" + "\\" + folder + "\\lib\\");
                String path = "c:\\Program Files" + "\\" + folder + "\\lib\\";
                folderList.add(folder);
                System.out.println(path);

            }

        }
        input.close();
        System.out.println("****");  // unreachable code error is I am not able to go out of the while loop. 

提前致谢。

您可以将您的bufferedreader放在try子句中,它会自动关闭。

String line;
Set<String> folderList = new HashSet<>();
Process p = Runtime.getRuntime()
            .exec(new String[] { "cmd", "/K", "dir \"c:\\Program Files\\apache-tomcat-*\" /s" });


try(BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
    while ((line = input.readLine().trim()) != null) {
        if (line.contains("<DIR>")) {

            String folder = line.substring(line.indexOf("<DIR>") + "<DIR>".length()).trim();
            // System.out.println("c:\\Program Files" + "\\" + folder + "\\lib\\");
            String path = "c:\\Program Files" + "\\" + folder + "\\lib\\";
            folderList.add(folder);
            System.out.println(path);

        }
    }
    System.out.println("****"); 
} catch (IOException e) {
    e.printStackTrace();
}

另外, (line = input.readLine().trim()) != null可能会在input.readLine()返回null时引发NullPointerException。

input.readLine()将返回null,以指示流结束。

如果readLine()返回null,则调用trim()将引发NullPointerException ,因此保证分配给line值不为null。

这意味着while (line != null) 始终为true ,因此循环永远不会结束。

编译器正确,循环后的代码不可访问。

您需要检查空值调用trim

while ((line = input.readLine()) != null) {
    line = line.trim();
    if (line.contains("<DIR>")) {

暂无
暂无

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

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