How to Read Entire Txt File Into String Java

Many times you want to read contents of a file into String, but, unfortunately, it was non a trivial job in Java, at to the lowest degree not until JDK 1.7. In Java 8, you can read a file into String in just one line of code. Prior to the release of new File IO API, you accept to write a lot of boilerplate lawmaking e.g. open an input stream, catechumen that input stream into a Reader, and then wrap that into a BufferedReader and and then on. Of grade, JDK ane.5's Scanner class did provide some breathing space only it was yet not as simple as it should be, like in Python or Ruby. By using Java vii new File API and Java 8'due south new features like lambda expression and stream API, Java is now close to Python or other utility languages, when information technology comes to reading the file into String.

In this article, you volition learn a couple of ways to read a file into Cord in just a couple of lines, mostly one line. Though, whenever you convert binary data into text data, you must remember to use correct grapheme encoding. An incorrect choice of grapheme encoding may result in totally unlike or slightly different content than the original file.

Some other advantage of using new features of JDK 8 such as lambda expression and streams are that they are lazy, which means better performance. It'south peculiarly benign if you only need a portion of file e.1000. all the lines which contain word "Mistake" or "Exception" or "Order" etc.

Reading File to String in Java

In order to understand the beauty of Java seven way of reading the file into String, beginning, let's see how nosotros used to exercise it in Java 1.v and 6.

          InputStream          is          =          new          FileInputStream("manifest.mf");          BufferedReader          buf          =          new          BufferedReader(new          InputStreamReader(is));          String          line          =          buf.readLine();          StringBuilder          sb          =          new          StringBuilder();          while(line          !=          null){    sb.suspend(line).append("\n");    line          =          buf.readLine(); }          Cord          fileAsString          =          sb.toString();          System          .out.println("Contents : "          +          fileAsString);

You can see that information technology's not easy, you need to write a lot of unnecessary boilerplate code. This is even when nosotros are just writing for the demo, forget about product quality lawmaking when you lot have to handle exceptions properly. Worth noting is that in this instance we are using platform's default grapheme encoding, which is fine because manifest.mf has non contained any graphic symbol other than ASCII, just information technology's not a rubber way if yous don't know the encoding, by default apply "UTF-eight". At present let's see how you can read a file every bit String in JDK 1.7

          String          contents          =          new          Cord(Files          .readAllBytes(Paths          .get("manifest.mf")));          System          .out.println("Contents (Java seven) : "          +          contents);

You lot tin can see there is no more wrapping effectually different class, no more loop, no more than handling of the special condition, just a method phone call to read the whole file into a byte array and then create String from it. Just like our previous example, this is as well using platform's default character encoding.

You tin also see Core Coffee for Impatient past Cay S. Horstmann, one of the meliorate books to larn subtle details of Java and it covers Java SE 8 as well.

How to read File as String in Java

Let'due south see how can nosotros provide a custom character encoding of our choice:

          Cord          fileString          =          new          String(Files          .readAllBytes(Paths          .get("manifest.mf")),          StandardCharsets                      .UTF_8);          System          .out.println("Contents (Java 7 with grapheme encoding ) : "          +          fileString);

Now does it get any simpler with Java 8 Streams and lambda expression, well it does, as we have seen in my earlier article most how to read file in Coffee 8, its same equally Java 7, how tin can you go less than one line, just yes you can use Stream and its lazy evaluation for your benefit :

          Files          .lines(Paths          .become("manifest.mf"),          StandardCharsets                      .UTF_8).forEach(System          .out:          :println);

You should get familiar with new File API, it'due south really helpful to practise efficient file IO in Java, as shown below:

How to read file into String in Java 8

Program to Read Contents of a File in Coffee eight

Here is the complete code sample of how to read the file as String in Java 5, 6, vii and viii. Y'all can come across that Coffee 7 has actually made it a picayune task.

          packet          test;          import          coffee.io.BufferedReader;          import          java.io.FileInputStream;          import          java.io.IOException;          import          java.io.InputStream;          import          java.io.InputStreamReader;          import          java.nio.charset.StandardCharsets;          import          java.nio.file.Files;          import          java.nio.file.Paths;          /**  * Coffee Plan to demonstrate different ways to loop over collection in   * pre Coffee viii and Java 8 world using Stream'due south forEach method.  *            @writer            Javin Paul  */          public          class          FileToStringJava8          {          public          static          void          main(String          args[])          throws          IOException          {          // How to read file into Cord before Java vii          InputStream          is          =          new          FileInputStream("manifest.mf");          BufferedReader          buf          =          new          BufferedReader(new          InputStreamReader(is));          String          line          =          buf.readLine();          StringBuilder          sb          =          new          StringBuilder();          while(line          !=          null){             sb.append(line).suspend("\n");             line          =          buf.readLine();         }          Cord          fileAsString          =          sb.toString();          System          .out.println("Contents (before Java 7) : "          +          fileAsString);          // Reading file into Stirng in ane line in JDK seven          String          contents          =          new          String(Files          .readAllBytes(Paths          .go("manifest.mf")));          System          .out.println("Contents (Java vii) : "          +          contents);          // Reading file into Cord using proper character encoding          String          fileString          =          new          String(Files          .readAllBytes(Paths          .get("manifest.mf")),          StandardCharsets                      .UTF_8);          System          .out.println("Contents (Java 7 with graphic symbol encoding ) : "          +          fileString);          // It's even easier in Java 8          Files          .lines(Paths          .go("manifest.mf"),          StandardCharsets                      .UTF_8).forEach(System          .out:          :println);              }   }        

That's all almost how to read the file into String in Java. Though this is good for the small tasks where you need contents of the file as String in your program, don't read a large file of few Gigabytes similar that, otherwise, your Java program will run out of retentiveness, instead use InputStream. Also, always recall to utilize character encoding while converting binary information to character information. If y'all are unsure, simply employ UTF-eight equally default.

In reality, unlike file provides character encoding metadata differently e.g. XML file as that as their first line header, HTML file defines character encoding in "Content-Blazon" attribute and so on. If you lot are using XML parser then you lot don't demand to worry as they accept a way to figure out right encoding by reading the file, aforementioned is the case if y'all are reading HTML using open source library.

Farther Learning

The Complete Coffee MasterClass
From Collections to Streams in Java eight
Refactoring to Java eight Streams and Lambdas Self- Study Workshop

If you lot like this article and want to learn more nearly improved file IO in recent Java version, please bank check following tutorials:

  • 3 ways to read a file line by line in Java eight (examples)
  • How to read a text file line past line using BufferedReader in Java? (reply)
  • How to use a memory mapped file in Coffee? (answer)
  • How to read an XML file every bit Cord in Java? (tutorial)
  • How to read/write Excel (both XLS and XLSX) files in Java using Apache POI? (tutorial)
  • ii ways to parse CSV file in Java? (reply)
  • How to read and write from/to RandomAccessFile in Java? (tutorial)
  • How to delete a directory with files in Java? (answer)

hope this helps

weddlepilthand.blogspot.com

Source: https://javarevisited.blogspot.com/2015/09/how-to-read-file-into-string-in-java-7.html

0 Response to "How to Read Entire Txt File Into String Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel