How can I get a Java print file?
I am trying to read lines from a text file in Java, but there is a lot going on. Is this the best way to do this? I am especially concerned with resource leaks.
import java.io.*;
public class Filing {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("/Users/thomaspovinelli/Desktop/apps.txt");
BufferedReader br = new BufferedReader(fr);
String buffer;
String fulltext="";
while ((buffer = br.readLine()) != null) {
System.out.println(buffer);
fulltext += buffer;
}
br.close();
fr.close();
}
}
import java.io.*;
Never import the full package. It is considered bad practice to do so. Instead, import what you need and only what you need.
Instead of just reading a Java print file then printing it, why don't you create a method that reads all line of a file and returns a list of all the lines? This way, you can do more with the result:
public static List getAllLines(File file) throws FileNotFoundException, IOException {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String buffer;
String fulltext="";
while ((buffer = br.readLine()) != null) {
System.out.println(buffer);
fulltext += buffer;
}
br.close();
fr.close();
}
I am especially concerned with resource leaks.
Since Java 7, there is such a thing as a try-with-resources statement, which automatically closes the reader when an exception occurs, which you are not doing here. Your current code has memory leaks!
With some other improvements:
public static List readAllLines(File file) {
List result = new LinkedList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
for (String current = reader.readLine(); current != null; current = reader
.readLine()) {
result.add(current);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
By the way, this is actually the code I use often to read all lines of a file.