Does Java has a one line instruction to read to a text file, like what C# has?
I mean, is there something equivalent to this in Java?:
String data =
No external libraries needed. The content of the file will be buffered before converting to string.
Path path = FileSystems.getDefault().getPath(directory, filename);
String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
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.
No external libraries needed. The content of the file will be buffered before converting to string.
String fileContent="";
try {
File f = new File("path2file");
byte[] bf = new byte[(int)f.length()];
new FileInputStream(f).read(bf);
fileContent = new String(bf, "UTF-8");
} catch (FileNotFoundException e) {
// handle file not found exception
} catch (IOException e) {
// handle IO-exception
}
Not quite a one liner and probably obsolete if using JDK 11 as posted by nullpointer. Still usefull if you have a non file input stream
InputStream inStream = context.getAssets().open(filename);
Scanner s = new Scanner(inStream).useDelimiter("\\A");
String string = s.hasNext() ? s.next() : "";
inStream.close();
return string;
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);
}
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.