read complete file without using loop in java

Adesh singh picture Adesh singh · Jan 5, 2013 · Viewed 179.9k times · Source

Possible Duplicate:
How to create a Java String from the contents of a file
Whole text file to a String in Java

I am trying to read the contents of a file using FileReader . But i want to read the file without reading a line by line . Is it possible to read the whole file without loop. I am using the following code

 try
 {
     File ff=new File("abc.txt");
     FileReader fr=new FileReader(ff);

     String s;
     while(br.read()!=-1)
     {
          s=br.readLine();
     }
 }

 catch(Exception ex)
 {
     ex.printStackTrace();
 }

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Jan 5, 2013

Java 7 one line solution

List<String> lines = Files.readAllLines(Paths.get("file"), StandardCharsets.UTF_8);

or

 String text = new String(Files.readAllBytes(Paths.get("file")), StandardCharsets.UTF_8);