Reputation: 23134
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?
Upvotes: 1
Views: 5127
Reputation: 121810
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...
Upvotes: 2