Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file content in java?

Tags:

java

java-io

to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

Scanner sc = new Scanner(new File("file.txt")); while(sc.hasNextLine()){     String str = sc.nextLine();                      } 

Does the java api provide a way to get the content with one line of code like:

String content = FileUtils.readFileToString(new File("file.txt")) 
like image 399
UpCat Avatar asked Apr 12 '11 20:04

UpCat


People also ask

How do I find the contents of a file?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

How do you load a file in Java?

Example 1: Java Program to Load a Text File as InputStream txt. Here, we used the FileInputStream class to load the input. txt file as input stream. We then used the read() method to read all the data from the file.


1 Answers

Not the built-in API - but Guava does, amongst its other treasures. (It's a fabulous library.)

String content = Files.toString(new File("file.txt"), Charsets.UTF_8); 

There are similar methods for reading any Readable, or loading the entire contents of a binary file as a byte array, or reading a file into a list of strings, etc.

Note that this method is now deprecated. The new equivalent is:

String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read(); 
like image 62
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet