The read() method reads in all the data into a single string. This is useful for smaller files where you would like to do text manipulation on the entire file. Then there is readline() , which is a useful way to only read in individual lines, in incremental amounts at a time, and return them as strings.
The readAllLines() method of the Files class allows reading the whole content of the file and stores each line in an array as strings.
apache commons-io has:
String str = FileUtils.readFileToString(file, "utf-8");
But there is no such utility in the standard java classes. If you (for some reason) don't want external libraries, you'd have to reimplement it. Here are some examples, and alternatively, you can see how it is implemented by commons-io or Guava.
Not within the main Java libraries, but you can use Guava:
String data = Files.asCharSource(new File("path.txt"), Charsets.UTF_8).read();
Or to read lines:
List<String> lines = Files.readLines( new File("path.txt"), Charsets.UTF_8 );
Of course I'm sure there are other 3rd party libraries which would make it similarly easy - I'm just most familiar with Guava.
Java 11 adds support for this use-case with Files.readString, sample code:
Files.readString(Path.of("/your/directory/path/file.txt"));
Before Java 11, typical approach with standard libraries would be something like this:
public static String readStream(InputStream is) {
StringBuilder sb = new StringBuilder(512);
try {
Reader r = new InputStreamReader(is, "UTF-8");
int c = 0;
while ((c = r.read()) != -1) {
sb.append((char) c);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
Notes:
Java 7 improves on this sorry state of affairs with the Files
class (not to be confused with Guava's class of the same name), you can get all lines from a file - without external libraries - with:
List<String> fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);
Or into one String:
String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// or equivalently:
StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(path)));
If you need something out of the box with a clean JDK this works great. That said, why are you writing Java without Guava?
In Java 8 (no external libraries) you could use streams. This code reads a file and puts all lines separated by ', ' into a String.
try (Stream<String> lines = Files.lines(myPath)) {
list = lines.collect(Collectors.joining(", "));
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With