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

102 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
  38. I accept there are numerous more pleasurable open doors ahead for people that took a gander at your site.
    safety course in chennai

    ReplyDelete
  39. 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.
    best rpa training in bangalore
    rpa training in bangalore | rpa course in bangalore
    RPA training in bangalore
    rpa training in chennai
    rpa online training

    ReplyDelete
  40. 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!
    Python training in bangalore
    Python course in pune
    Python training in bangalore

    ReplyDelete

  41. This is quite educational arrange. It has famous breeding about what I rarity to vouch.
    Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved.
    This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.


    Selenium interview questions and answers
    Selenium Online training
    Selenium training in Pune
    selenium training in USA
    selenium training in chennai

    ReplyDelete
  42. Have you been thinking about the power sources and the tiles whom use blocks I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post
    python Training institute in Chennai
    python Training institute in Bangalore
    python Training in Pune

    ReplyDelete
  43. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article. thank you for sharing such a great blog with us.
    python Training institute in Chennai
    python Training institute in Bangalore
    python Training in Pune

    ReplyDelete
  44. Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for developing their skill to get good career.
    Python Online training
    python Course institute in Chennai
    Python Course institute in Bangalore

    ReplyDelete
  45. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    AWS Online Training
    AWS Training in Bangalore

    ReplyDelete
  46. Its a good post and keep posting good article.its very interesting to read.
    CCNA Training Institute Training in Chennai

    ReplyDelete
  47. This is really impressive post, I am inspired with your post, do post more blogs like this, I am waiting for your blogs.
    Regards,
    Devops Training in Chennai | Devops Certification in Chennai

    ReplyDelete
  48. I really like your blog. You make it interesting to read and entertaining at the same time. I cant wait to read more from you.

    informatica mdm online training

    apache spark online training

    angularjs online training

    devops online training

    aws online training

    ReplyDelete
  49. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  50. Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting.So know it's helpful.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete
  51. I am obliged to you for sharing this piece of information here and updating us with your resourceful guidance. Hope this might benefit many learners. Keep sharing this gainful articles and continue updating for us.
    apple service center in chennai
    apple mobile service centre in chennai
    apple service center near me

    ReplyDelete
  52. It is a great post. Keep sharing such kind of useful information.

    Education
    Technology

    ReplyDelete
  53. And indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
    SOFTWARE TRAINING IN CHENNAI
    POWERBI TRAINING IN CHENNAI
    CCNA TRAINING IN CHENNAI
    ANDROID TRAINING IN CHENNAI

    ReplyDelete
  54. nice course. thanks for sharing this post this post harried me a lot.
    MCSE Training in Noida

    ReplyDelete
  55. Idiotic and additionally trusting people at the same time can be an obstacle, on aged and also fully grown folk assembled also will follow a complication. Age and also embryonic concern together. VN Machine

    ReplyDelete
  56. I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information.Read This Guide

    ReplyDelete
  57. QuickBooks Payroll Support Phone Number management quite definitely easier for accounting professionals. There are so many individuals who are giving positive feedback if they process payroll either QB desktop and online options.

    ReplyDelete
  58. Attend The Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Bangalore.

    ReplyDelete
  59. QuickBooks Customer Support Number clients come back to us many times. We keep every one of the data safe plus in secrecy. We are going to never share it with other people. Thus, you'll be able to rely on us when it comes to nearly every data.

    ReplyDelete
  60. QuickBooks Payroll Support Number find fewer options available for the client to talk directly to agents or support executives for help. Posting questions on payroll community page is a good idea not the best way to obtain a sudden solution; in the event that you wanna to keep in contact with a person.

    ReplyDelete
  61. The primary functionality of QuickBooks Customer Support Number is dependent upon company file. Based on the experts, if you want solve the specific situation, then you'll definitely definitely definitely need to accept it first.

    ReplyDelete
  62. Keeping these records in your records will be quite useful to maintain your account along with information pertaining to federal along side state agencies.
    Well! The QuickBooks Enterprise Support Number world is extremely crucial and important as well.

    ReplyDelete
  63. Our QuickBooks 24 Hour Customer Service channel- We understand the complexity and need with this accounting software in day to day life. You can’t watch for pretty much time and energy to get a fix of each and every single QB error. Therefore we have designed a especially dedicated team of certified professionals at QuickBooks Technical Support contact number who are effective at understanding your issues and errors in minimum time as well as in probably the most convenient way. Dial our toll-free and avail the QuickBooks Support Phone Number available at the essential pocket friendly price.

    ReplyDelete
  64. The Quickbooks Payroll Support Phone Number team at site name is held responsible for removing the errors that pop up in this desirable software. We care for not letting any issue can be purchased in in the middle of your work and trouble you in undergoing your tasks. Many of us resolves most of the QuickBooks Payroll issue this type of a fashion that you'll yourself believe that your issue is resolved without you wasting the time into it. We take toll on every issue through the use of our highly trained customer care.

    ReplyDelete
  65. Our support team is engaged in pre-research to produce themselves prepared in advance when it comes to possible errors of QuickBooks Support Phone Number. This practice helps them produce you the specified end up in the given time window. Our company is there to help you 24*7 once we usually do not disassociate ourselves together with your troubles even through the wee hours.

    ReplyDelete

  66. Thanks for sharing the valuable information here. So i think i got some useful information with this content. Thank you and please keep update like this informative details.


    erp software development company in us
    erp software company in us
    list of erp software companies in us
    list of erp software companies in chennai
    Latest CRM Software

    ReplyDelete
  67. QuickBooks Support Number advisors are certified Pro-advisors’ and has forte in furnishing any type of technical issues for QuickBooks. These are generally expert and certified technicians of the domains like QuickBooks accounting,QuickBooks Payroll, Point of Sales, QuickBooks Merchant Services and Inventory issues to provide 24/7 service to our esteemed customers. QuickBooks payroll Services provide approaches to all your valuable QuickBooks problem and in addition assists in identifying the errors with QuickBooks data files and diagnose them thoroughly before resolving these issues.

    ReplyDelete