如何在Java中结束输入流

时间:2019-01-22 06:02:00

标签: 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. 

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以将您的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返回null时,input.readLine()可能会引发NullPointerException。

答案 1 :(得分:0)

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

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

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

编译器正确,循环后的代码无法访问。

您需要在检查空值之后调用trim

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