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"))
  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){
  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 =!=-1){
       char ch = (char)i;
       fileContents = fileContents + ch; 
  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!
     try {
        String str = FileUtils.readFileToString(new File("test.txt"));
      } catch (IOException e) {
Any more?? Please tell me, I'll add it to the list above and into my brain. Thanks for reading!!


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

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

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

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

    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


  2. This comment has been removed by the author.

  3. This comment has been removed by the author.

  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

  5. This comment has been removed by the author.

  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

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

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

  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.

  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

  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

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

  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

  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

  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

  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

  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

  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