How To Read Contents Of A File Into A String in One Line of Java Code?
Today we will share with you one quick and dirty tip using which you can get or read the contents of a given file in Java using just one line of code. This trick will be very useful when you will have to quickly read a mission critical-file such as a configuration file of an application.
You might argue using something like a Filereader or bufferreader to acces and read the contents of any text file in Java. However, just take a look at the following snippet of code:
String fileContents = new Scanner( new File("/path/to/file") ).useDelimiter("\\A").next();
The above snippet of code simply puts the content of the file "/path/to/file" as a string into the variable fileContents. You might ask how it just happened. Here is how it goes:
1. We create a new file object of the required file, that is to be read.
2. Then we pass this file object into a new Scanner object type.
3. We then set the delimiter to set read the tokens to \\A. this regular expression will get the contents of the file from start.
Please let us know if you like this tip. ANother alternate version of the code will be:
String fileContents = new Scanner( new File("/path/to/file") ).useDelimiter("\\Z").next();