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!!

55 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
  11. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and Ihope you post again soon. Big thanks for the useful info.Very informative blog post about creating a Jmenuapp in Java. Especially if you are a beginner, this post will really help. I am going to bookmark your blog for future readings. Keep up the good work!
    AngularJS Training Institute in Chennai
    AngularJS Cetification Training in Chennai
    AWS Training in Chennai
    AWS Devops Training in Chennai
    DevOps Certification in Chennai
    DevOPs Certification Training Institute in Chennai
    Best AngularJS Training in Chennai
    AngularJS Training in Chennai

    ReplyDelete
  12. It was really a nice article and i was really impressed by reading this Big data hadoop online training HYDERABAD

    ReplyDelete
  13. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune

    rpa online training

    ReplyDelete
  14. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    Click here:
    angularjs6 Training in Chennai
    Click here:
    Microsoft azure training in chennai
    Click here:
    angularjs6 Training in Chennai
    Click here:
    angularjs Training in online

    ReplyDelete
  15. I have been meaning to write something like this on my website and you have given me an idea. Cheers.
    Click here:
    Microsoft azure training in marathahalli
    Click here:
    Microsoft azure training in bangalore
    Click here:
    Microsoft azure training in pune

    ReplyDelete
  16. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    DevOps online Training|DevOps Training in USA
    Devops Training in Chennai

    Devops Training in Bangalore

    ReplyDelete
  17. Fantastic work! This is the type of information that should follow collective approximately the web. Embarrassment captivating position Google for not positioning this transmit higher! Enlarge taking place greater than and visit my web situate
    python training in Bangalore
    python training in pune
    python online training
    python training in chennai

    ReplyDelete
  18. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    Blueprism training in Bangalore

    Blueprism training in Pune

    Blueprism training in Chennai

    ReplyDelete
  19. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging

    Azure Training
    Azure Training in Chennai

    ReplyDelete
  20. Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
    nebosh courses in chennai

    ReplyDelete
  21. UiPath Training in Bangalore by myTectra is one the best UiPath Training. myTectra is the market leader in providing Robotic Process Automation on UiPath
    robotic process automation training in bangalore

    ReplyDelete
  22. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging
    SAP PP Training From India

    SAP Abap On Hana Training From India

    Exchange Server Training From India

    ReplyDelete
  23. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Best Sailpoint Online Training From India
    Best Dotnet Online Training From India
    Best Java Online Training From India

    ReplyDelete
  24. Well researched article and I appreciate this. The blog is subscribed and will see new topics soon.
    Dell Boomi Selfplaced Videos

    Hyperion Essabse Selfplaced Videos

    Microsoft Azure Selfplaced Videos

    ReplyDelete
  25. Great post and informative blog.it was awesome to read, thanks for sharing this great content to my vision.
    Good discussion.
    Six Sigma Training in Abu Dhabi
    Six Sigma Training in Dammam
    Six Sigma Training in Riyadh

    ReplyDelete
  26. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Best Training From India Instittue

    Best Training From India Instittue

    Best Training From India Instittue

    ReplyDelete
  27. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me..
    Online IT Training Videos

    AWS Training Videos

    Golden Gate Training Videos

    ReplyDelete
  28. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    ReplyDelete
  29. Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    windows server Online Training

    Powershell Online Training

    Android Online Training

    Linux Online Training

    ReplyDelete
  30. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.

    Data Science course in kalyan nagar | Data Science course in OMR
    Data Science course in chennai | Data science course in velachery
    Data science course in jaya nagar | Data science training in tambaram

    ReplyDelete
  31. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    AWS Interview Questions And Answers

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  32. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

    java training in annanagar | java training in chennai

    java training in chennai | java training in electronic city

    ReplyDelete
  33. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email. I’ve got some recommendations for your blog you might be interested in hearing.
    AWS Training in Chennai |Best Amazon Web Services Training in Chennai
    AWS Training in Rajaji Nagar | Amazon Web Services Training in Rajaji Nagar

    Best AWS Training Institute in BTM Layout Bangalore ,AWS Coursesin BTM

    ReplyDelete
  34. Greetings from Florida! I’m bored at work, so I decided to browse your site on my iPhone during lunch break.
    safety course institute in chennai

    ReplyDelete
  35. Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!
    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    ReplyDelete
  36. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    selenium training in chennai
    selenium training in bangalore
    selenium training in Pune
    selenium training in pune
    Selenium Online Training


    https://maxood-android-corner.blogspot.com/2011/01/tutorial-android-mind-games.html


    ReplyDelete
  37. Thank you for sharing your article. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.
    Data Science Training in chennai at Credo Systemz | data science course fees in chennai | data science course in chennai quora | data science with python training in chennai

    ReplyDelete