简体   繁体   中英

Use try-with-resource to read a text file line by line in java

For example, here is one way to read a text file line by line:

ArrayList<String> fidiidList = new ArrayList<String>();
String sampleLine;

String fileStem = "/tmp/x.txt";
File sampleFile = new File(fileStem);
BufferedReader sampleBuffer = new BufferedReader(new FileReader(sampleFile));
while ((sampleLine = sampleBuffer.readLine()) != null) {
    fidiidList.add(sampleLine);
}
sampleBuffer.close();

You have to close the buffer manually. I am wondering if it's ok to do it this way:

try(BufferedReader sampleBuffer = new BufferedReader(new FileReader(sampleFile))) {
    while ((sampleLine = sampleBuffer.readLine()) != null) {
        fidiidList.add(sampleLine);
    }
} catch (Exception e) {
    e.printStackTrace();
}

Which according to my textbook promises to close objects automatically.

BTW, when I type this in my IDE, it reminds me to bring language level from 1.8 to 1.7, does this mean Java 8 stopped supporting this feature?

You are using Java 7. Use Java 7's file API:

final List<String> allLines 
    = Files.readAllLines(pathToYourFile, StandardCharsets.UTF_8);

Since Java 8 you can even obtain a Stream of all lines in a file using Files.lines() .


As to your IDE telling you to bring language level to 1.7, it is probably because you don't use Java 8 features.


Other side note: I highly doubt that you will be able to read text lines from a PDF, as your code seems to attempt doing...

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