Explain Codes LogoExplain Codes Logo

Reading a plain text file in Java

java
file-handling
buffered-reader
try-with-resources
Anton ShumikhinbyAnton Shumikhin·Sep 9, 2024
TLDR

To read a text file into a List<String> in Java, leverage the NIO's Files.readAllLines() method. Make sure you supply the correct file Path and Charset for encoding.

List<String> lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8); lines.forEach(System.out::println);

This snippet opens "file.txt", reads its content and prints it out, with UTF-8 serving as the charset encoding. Don't forget to handle or throw the IOException.

Efficient BufferedReader coupled with Java 7's try-with-resources

Thanks to Java 7, we have the try-with-resources statement that allows you to declare resources, such as a BufferedReader, to be automatically closed once the program exits the block. Here's an example:

Path path = Paths.get("file.txt"); try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append(System.lineSeparator()); } System.out.println(content.toString()); } catch (IOException e) { e.printStackTrace(); // When life gives you exceptions, printStackTrace()! }

Note that for binary data files, you'd want to use InputStream subclasses. For high-speed file reading, Files.readAllBytes can help read the file content into a byte array and then convert it to a String.

Power of Functional Style: Java 8’s Files.lines()

Java 8 presented the Files.lines() function that helps retrieve a Stream<String>. It allows a more efficient and functional style of processing:

try (Stream<String> lines = Files.lines(Paths.get("file.txt"), StandardCharsets.UTF_8)) { lines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); // Print me baby one more time! }

Simplifying Code with Apache Commons IO

Apache's Commons IO has the IOUtils.toString() method in its toolkit which reads an entire file into a String in one go:

String content = IOUtils.toString(new FileInputStream("file.txt"), StandardCharsets.UTF_8);

You've got to handle exceptions and cleanly close the input stream afterwards, just like cleaning up after a party!

Large files: The BufferedReader superhero

Dealing with large text files requires the resourceful BufferedReader. This superhero allows you to process text as you read:

try (BufferedReader reader = new BufferedReader(new FileReader("bigfile.txt"))) { String line; while ((line = reader.readLine()) != null) { // Process the line - enjoy the ride! } } catch (IOException e) { e.printStackTrace(); // Whoops! Exception slip-n-slide! }

Pay attention to character encoding

Character encoding can get tricky. If you use FileReader without specifying the encoding, it'll use the default one, which might mess up your data. So, always specify the encoding!

The right tool for the job

Different file handling tasks, different tools:

  • Small Files: No fuss. Use Files.readAllLines().
  • Large Text Files: Arm yourself with the BufferedReader.
  • Binary Files: InputStream subclasses to the rescue.
  • Coding simplicity: Invoke the power of Apache Commons IO.
  • Stream Operations: Ride the wave with Files.lines().

Exception? No Exception with Error handling

Cover your code with try-catch armor to sweep away any pesky unhandled exceptions. They may scar your program if not treated well.

Encapsulation is your friend

Pack your file reading logic into a reusable method like readFile. It makes your code more modular and maintainable - and your life, a lot easier!