简体   繁体   中英

How to end the input stream in java

I am trying to close inputstream using input.close(), but I am unable to do so.

              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. 

Thanks in advance.

you can put your bufferedreader in a try clause and it gets automatically closed.

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();
}

Also, (line = input.readLine().trim()) != null has the potential to throw an NullPointerException when input.readLine() returns null.

input.readLine() will return null to indicate end-of-stream.

Calling trim() will throw NullPointerException if readLine() returned null, so value assigned to line is guaranteed to not be null.

That means while (line != null) is always true , and hence the loop will never end.

The compiler is correct, the code after the loop is unreachable.

You need to call trim after checking for null value:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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