How to read a file in Java

This article focus on a few of the commonly used methods to read a file in Java. Files.lines, return a Stream (Java 8) Files.readString, returns a String (Java 11), max file size 2G. Files.readAllBytes, returns a byte[] (Java 7), max file size 2G. Files.readAllLines, returns a List<String> (Java 8) BufferedReader, a classic old friend (Java …

Read more

Java Files.readAllBytes example

In Java, we can use Files.readAllBytes to read a file. byte[] content = Files.readAllBytes(Paths.get("app.log")); System.out.println(new String(content)); 1. Text File A Java example to write and read a normal text file. FileExample1.java package com.mkyong.calculator; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; public class FileExample1 { public static void main(String[] …

Read more

Java – How to list all files in a directory?

Two Java examples to show you how to list files in a directory : For Java 8, Files.walk Before Java 8, create a recursive loop to list all files. 1. Files.walk 1.1 List all files. try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.filter(Files::isRegularFile) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); …

Read more

How to write to file in Java – BufferedWriter

In Java, we can use BufferedWriter to write content into a file. // jdk 7 try (FileWriter writer = new FileWriter("app.log"); BufferedWriter bw = new BufferedWriter(writer)) { bw.write(content); } catch (IOException e) { System.err.format("IOException: %s%n", e); } Note If possible, uses Files.write instead, one line, simple and nice. List<String> list = Arrays.asList("Line 1", "Line 2"); …

Read more