What's the process of a Java print file?

559    Asked by AmitSinha in Java , Asked on Oct 14, 2022

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/thomas povinelli/Desktop/apps.txt");
        BufferedReader br = new BufferedReader(fr);
        String buffer;
        String full text="";
        while ((buffer = br.readLine()) != null) {
            System.out.println(buffer);
            full text += buffer;
        }
        br.close();
        fr.close();
    }
}
Answered by Amit Sinha
  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.

 This way, you can do more with the result of Java print file:
public static List getAllLines(File file) throws FileNotFoundException, IOException {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String buffer;
    String full text="";
    while ((buffer = br.readLine()) != null) {
        System.out.println(buffer);
        full text += buffer;
    }
    br.close();
    fr.close();
}
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.



Your Answer

Interviews

Parent Categories