Java is very flexible language in terms of functionalities and utilities available for use to use out of the box.
There is no way you have create your own utility for operations. Just import available packages and use function to achieve your goal.
Some time back we have written few articles on how to read file in Java line by line. One example is read file in reverse order and second is related to read file using Java 8 Stream operations.
Both articles are well received by the user. It worked for all of my readers but recently I got a comment on one of the article.
Thanks Dusan
for posting a comment on it. Instead of just writing code as a comment reply I thought of creating new tutorial for the same question.
Let’s go over steps on how to read file without Java Loop at a once. Here is a complete example:
package crunchify.com.tutorials; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * @author Crunchify.com * How to Read Complete File at a once in Java without using any Loop? */ public class CrunchifyReadFileAtaOnce { public static void main(String[] args) { File crunchifyFile = new File("/Users/ashah/Documents/crunchify-file.txt"); FileInputStream fileInputStream; try { fileInputStream = new FileInputStream(crunchifyFile); byte[] crunchifyValue = new byte[(int) crunchifyFile.length()]; fileInputStream.read(crunchifyValue); fileInputStream.close(); String fileContent = new String(crunchifyValue, "UTF-8"); log(fileContent); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void log(String str) { System.out.println(str); } }
Eclipse console output:
{ "blogURL": "https://crunchify.com", "twitter": "https://twitter.com/Crunchify", "social": { "facebook": "http://facebook.com/Crunchify", "pinterest": "https://www.pinterest.com/Crunchify/crunchify-articles", "rss": "https://crunchify.com/feed/" } }
This is the same text content which I have put into file and reading in above file. Make sure you change file path if you are running above program in Windows environment.
Hope you get clear picture on reading file without Java Loop and iteration 🙂