(Copied from http://www.vogella.com/tutorials/JavaIO/article.html)
Java provides a standard way of reading from and writing to files. Traditionally the java.io
package was used, but in modern Java applications you use the java.nio.file
API.
Java will read all input as a stream of bytes. The InputStream class is the superclass of all classes representing an input stream of bytes.
To read a text file you can use the Files.readAllBytes
method. The usage of this method is demonstrated in the following listing.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
// somewhere in your code
String content = new String(Files.readAllBytes(Paths.get(fileName)));
To read a text file line by line into a List
of type String
structure you can use the Files.readAllLines
method.
List<String> lines = Files.readAllLines(Paths.get(fileName));
Files.readAllLines
uses UTF-8 character encoding. It also ensures that file is closed after all bytes are read or in case an exception occurred.
The Files.lines
method allows read a file line by line, offering a stream. This stream can be filtered and mapped. Files.lines
does not close the file once its content is read, therefore it should be wrapped inside a try-with-resource statement.
In the following example unnecessary whitespace at the end of each line is removed and empty lines are filterer.
//read all lines and remove whitespace (trim)
//filter empty lines
//and print result to System.out
Files.lines(new File("input.txt").toPath())
.map(s -> s.trim())
.filter(s -> !s.isEmpty())
.forEach(System.out::println);
The next example demonstrates how to filter out lines based on a certain regular expression.
Files.lines(new File("input.txt").toPath())
.map(s -> s.trim())
.filter(s -> !s.matches("yourregularexpression"))
.forEach(System.out::println);
The next example extracts a line starting with "Bundle-Version:" from a file called "MANIFEST.MF" located in the "META-INF" folder. It removes the prefix and removes all leading and trailing whitespace.
package com.vogella.eclipse.ide.first;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.stream.Stream;
public class ReadMANIFESTFile {
public static void main(String[] args) throws IOException {
String versionString = readStreamOfLinesUsingFiles();
System.out.println(versionString);
}
private static String readStreamOfLinesUsingFiles() throws IOException {
Stream<String> lines = Files.lines(Paths.get("META-INF", "MANIFEST.MF"));
Optional<String> versionString = lines.filter(s -> s.contains("Bundle-Version:")).map(e-> e.substring(15).trim()).findFirst();
lines.close();
if (versionString.isPresent())
{
return versionString.get();
}
return "";
}
}