Monday, May 28, 2012

Java : How To Read a Complete Text File into a String

One of the most overwhelming topics for any Java newbie is the File I/O and a simple reading of a file which seems so easy in C becomes cryptic with so many classes involved. I plan to document all those different ways to Read A Complete File into a String.

Java Code(s) for Reading An Entire Text File into a String


  1. Using the Scanner class.


    public class ReadEntireFileIntoAString {
     public static void main(String[] args) throws FileNotFoundException {
    
      String entireFileText = new Scanner(new File("readme.txt"))
        .useDelimiter("\\A").next();
    
      System.out.println(entireFileText);
     }
    }
    
  2. Using the BufferedReader to read line by line.

    But remember, we need to add a "\n" at the end, since readline strips the new line at the end
    public class ReadFileIntoAStringLineByLine {
    
     public static void main(String[] args) throws IOException {
    
      BufferedReader bufferedReader = new BufferedReader(new FileReader("readme.txt"));
    
      StringBuffer stringBuffer = new StringBuffer();
      String line = null;
    
      while((line =bufferedReader.readLine())!=null){
    
       stringBuffer.append(line).append("\n");
      }
      
      System.out.println(stringBuffer);
     }
    }
    
  3. Using the barebones  FileReader to read character by character using the read() method.

    We are avoiding an extra wrapper, the BufferedReader that offers us more tools, one of which we saw above. If you are using any other character set other than the default, use an InputSreamReader or a FileInputStream  to set the encoding.
    public class ReadEntireFileIntoAStringCharByChar {
    
     public static void main(String[] args) throws IOException {
      FileReader fileReader = new FileReader("readme.txt");
       
      String fileContents = "";
    
      int i ;
    
      while((i =  fileReader.read())!=-1){
       char ch = (char)i;
    
       fileContents = fileContents + ch; 
      }
    
      System.out.println(fileContents);
     }
    }
  4. The most Beautiful of them all! The Apache CommonsIO library's FileUtils class.

    However, the tradeoff is that you need to download the library and add it to your classpath. It also has overloaded versions of the readFileToString method with the charset encoding. Do check it out!
     import org.apache.commons.io.FileUtils;
     try {
        String str = FileUtils.readFileToString(new File("test.txt"));
        System.out.println(str);
      } catch (IOException e) {
         e.printStackTrace();
     }
    
Any more?? Please tell me, I'll add it to the list above and into my brain. Thanks for reading!!

16 comments:

  1. Thanks Mate
    Your post is a life saver
    Thank you :)

    ReplyDelete
    Replies
    1. Life Saver? Ha Ha Ha... Thanks for those encouraging words :)

      Delete
    2. Hi,I m getting error "cannot convert from string to string" while using any of the above method.

      Delete
    3. Hi,I m getting error "cannot convert from string to string" while using any of the above method.

      Delete
    4. Use Java NIO


      byte[] bytes = Files.readAllBytes(Paths.get("D:\\test.txt"));
      String str = new String(bytes, StandardCharsets.UTF_8);

      Full Source...Java Simple Read File

      Ling

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Very useful and nice article thx Abhinandan...

    would like to read more on same topic.

    refer my post:-
    how to read files content as string/text in java

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  7. How would I break this out line by line into different strings?

    ReplyDelete
  8. Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.java training in chennai | chennai's no.1 java training in chennai | best java institute in chennai

    ReplyDelete
  9. This is the best article that I have read on How To Read a Complete Text File into a String and being a JAVA student it has improve my general programming knowledge and skills and I am looking forward to reading more creative programming articles from this site. Kindly, find time and read my article by clicking on Developing the Skills to Write a Dissertation Within a Week.

    ReplyDelete
  10. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.
    Selenium Training in Chennai | Hadoop Training in Chennai | Java Training in Chennai

    ReplyDelete