Sometimes, the most helpful updates aren’t the massive new frameworks, but the small utility methods that make our daily coding lives easier. Java 11 introduced several “quality of life” improvements to the String and Files classes that eliminate common boilerplate.
1. String API Enhancements
Before Java 11, checking if a string was just whitespace or repeating a string required external libraries like Apache Commons or custom loops. Now, it’s built-in.
isBlank()
Checks if a string is empty or contains only white space characters.
String empty = " ";
System.out.println(empty.isEmpty()); // false (length is not 0)
System.out.println(empty.isBlank()); // true (contains only whitespace)
lines()
Returns a Stream of strings extracted from this string, separated by line terminators.
String poem = "Line 1\nLine 2\r\nLine 3";
poem.lines()
.filter(line -> !line.isBlank())
.forEach(System.out::println);
repeat(int n)
Repeats the string content n times.
String star = "*";
System.out.println(star.repeat(5)); // *****
strip(), stripLeading(), and stripTrailing()
A more modern version of trim(). While trim() only removes characters with ASCII values less than or equal to space, strip() is Unicode-aware and removes all characters classified as white space by the Unicode standard.
String greeting = "\u2001 Hello \u2001"; // Contains Unicode whitespace
System.out.println("'" + greeting.trim() + "'"); // Might miss Unicode spaces
System.out.println("'" + greeting.strip() + "'"); // Cleanly stripped
2. Files API Enhancements
Reading and writing small text files used to involve BufferedReader, FileWriter, and a lot of try-with-resources blocks. Java 11 simplifies this for common scenarios.
writeString()
Writes a string to a file in one line.
import java.nio.file.Files;
import java.nio.file.Path;
public class FileWriteExample {
public static void main(String[] args) throws Exception {
Path path = Path.of("notes.txt");
Files.writeString(path, "Java 11 makes file I/O easy!");
}
}
readString()
Reads the entire content of a file into a string.
String content = Files.readString(Path.of("notes.txt"));
System.out.println(content);
Real-World Example: Processing a CSV Snippet
Imagine you have a small CSV string and you want to clean it up and save it to a file.
String csvData = " name , age , city \n John , 30 , NY \n , , ";
// Clean up: filter out empty lines and strip padding
String cleanedCsv = csvData.lines()
.filter(line -> !line.isBlank())
.map(line -> line.strip())
.reduce((a, b) -> a + "\n" + b)
.orElse("");
// Save to disk
Files.writeString(Path.of("output.csv"), cleanedCsv);
Conclusion
The enhancements to String and Files in Java 11 are perfect examples of the “less is more” philosophy. By providing these native utilities, Java 11 reduces the need for “util” classes and external dependencies, leading to cleaner, more maintainable codebases.