Java 8 Read All Bytes From Inputstream and Returns String

Reading a file in Coffee is pretty unproblematic, we simply can use FileInputStream to read the contents of a file, but if you want to exercise some operations on the content which is read such as validation, pattern matching, etc, then it would exist easier to perform on the Cord rather than the InputStream. In this article, we will encounter the different ways to convert InputStream to String in Java. We will exist using the Native Java and 3rd party libraries similarApache Commons IO andGuava.

ix Dissimilar ways to catechumen InputStream to String in Java?

Convert InputStream to String

one. Convert InputStream to Cord using BufferedReader

This is the easiest way to convert InputStream to String and well known to about all the Java developers.

  • Read the content of the file using the InputStream
  • Pass the inputStream to the constructor of InputStreamReader instance and laissez passer InputStreamReaderto the constructor of the BufferedReader
  • Append each line of the file returned by the bufferedReader to the StringBuilder object
package com.javainterviewpoint;  import coffee.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import coffee.io.InputStream; import coffee.io.InputStreamReader;  public course InputStreamToString {     public static void main(String[] args)     {         InputStream inputStream = null;         BufferedReader bufferedReader = zip;                  StringBuilder stringBuilder = new StringBuilder();         String text;         try         {             inputStream = new FileInputStream (new File("D:\\temp.txt"));             bufferedReader = new BufferedReader (new InputStreamReader(inputStream));             while ((text = bufferedReader.readLine()) != null )             {                 stringBuilder.append(text);             }             System.out.println(stringBuilder);         } grab (FileNotFoundException due east)         {             due east.printStackTrace();         } catch (IOException e)         {             e.printStackTrace();         }     } }

Output:

Convert InputStream to String with BufferedReader

2. Convert using Scanner

  • Read the content of the file using the InputStream
  • The InputStream instance and the charset (UTF-viii) is passed to the constructor of the Scanner
  • Nosotros have used the delimiter as "\\northward" so that the scanner reads line by line.
  • Append each line of the file returned by the s canner.next()to the StringBuilder object
packet com.javainterviewpoint;  import coffee.io.File; import coffee.io.FileInputStream; import coffee.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Scanner;  public class InputStreamToString {     public static void main(Cord[] args)     {         InputStream inputStream = null;         Scanner scanner = nothing;                  StringBuilder stringBuilder = new StringBuilder();         endeavour         {             inputStream = new FileInputStream (new File("D:\\temp.txt"));             scanner = new Scanner(inputStream, "UTF-eight").useDelimiter("\\northward");             while (scanner.hasNext())             {                 stringBuilder.append(scanner.side by side());             }             System.out.println(stringBuilder);         } catch (FileNotFoundException east)         {             due east.printStackTrace();         }     } }

iii. Using Stream API Collect

  • InputStream reads the file, pass the inputStreamReader instance to the constructor of the BufferedReader
  • BufferedReader returns a stream and it is converted into a String using the joining() method of Collectors Class
  • The collect() method collect together the desired results into a result container such as a Collection and the joining() method joins diverse elements of a character or string array into a single String object
package com.javainterviewpoint;  import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.stream.Collectors;  public class InputStreamToString {     public static void main(String[] args)     {         InputStream inputStream = aught;         try         {             inputStream = new FileInputStream (new File("D:\\temp.txt"));                          String outcome = new BufferedReader(new InputStreamReader(inputStream)).lines()                     .collect(Collectors.joining("\northward"));                          Arrangement.out.println(result);         } catch (FileNotFoundException due east)         {             eastward.printStackTrace();         }      } }

4. Using parallel

We have additionally added parallel() to the above code, Parallel Streams requite the states the flexibility to iterate in a parallel pattern, but information technology has its equal performance impacts as each sub-stream is a single thread running and acting on the data, it has overhead compared to the sequential stream

package com.javainterviewpoint;  import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.stream.Collectors;  public class InputStreamToString {     public static void principal(String[] args)     {         InputStream inputStream = null;         endeavor         {             inputStream = new FileInputStream (new File("D:\\temp.txt"));                          Cord effect = new BufferedReader(new InputStreamReader(inputStream)).lines()                     .parallel().collect(Collectors.joining("\n"));                          Arrangement.out.println(result);         } catch (FileNotFoundException e)         {             eastward.printStackTrace();         }      } }

5. Using ByteArrayOutputStream

  • Read the input file using InputStream and Create an case for ByteArrayOutputStream.
  • The read() method returns the next byte of data and returns -ane when it is the finish of the stream, read the content using a while loop till the end of the stream
  • Now call the write() method on superlative of the byteArrayOutputStream instance passing the buffer byte.
package com.javainterviewpoint;  import java.io.ByteArrayOutputStream; import coffee.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import coffee.io.IOException; import java.io.InputStream;  public course InputStreamToString {     public static void main(String[] args)     {         InputStream inputStream = zilch;         try         {             inputStream = new FileInputStream (new File("D:\\temp.txt"));                          ByteArrayOutputStream result = new ByteArrayOutputStream();             byte[] buffer= new byte[512];             while ((inputStream.read(buffer)) != -1) {                 result.write(buffer);             }                          Arrangement.out.println(event);         } take hold of (FileNotFoundException eastward)         {             eastward.printStackTrace();         } grab (IOException e)         {             due east.printStackTrace();         }      } }

6. Using IOUtils toString

Apache Commons provides the IOUtils class to read content from a file. In order to utilize the eatables-io (Apache Commons) library, we need to add the below maven dependency

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>ii.six</version>
</dependency>

We volition exist using toString() and copy() method of IOUtils class to Catechumen InputStream to Cord

Using the toString() of Apache Commons is pretty simple. The toString() method reads data from a stream, all we need to do is that read the file using inputStream and pass it to the toString() method along with the Charset.

package com.javainterviewpoint;  import java.io.File; import coffee.io.FileInputStream; import coffee.io.FileNotFoundException; import java.io.IOException; import coffee.io.InputStream; import java.nio.charset.StandardCharsets;  import org.apache.eatables.io.IOUtils;   public class InputStreamToString {     public static void primary(String[] args)     {         InputStream inputStream = null;         try         {             inputStream = new FileInputStream (new File("D:\\temp.txt"));                          String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);                          Organisation.out.println(issue);         } catch (FileNotFoundException e)         {             due east.printStackTrace();         } catch (IOException e)         {             e.printStackTrace();         }      } }

7. Using IOUtils Re-create

The re-create() method copies all the data from one stream to another, the content of the inputStream volition be copied to the StringWriter.

package com.javainterviewpoint;  import java.io.File; import coffee.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import coffee.nio.charset.StandardCharsets;  import org.apache.eatables.io.IOUtils;  public course InputStreamToString {     public static void main(String[] args)     {         InputStream inputStream = zero;         try         {             inputStream = new FileInputStream (new File("D:\\temp.txt"));                          StringWriter author = new StringWriter();             IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);             Organization.out.println(writer.toString());         } grab (FileNotFoundException e)         {             e.printStackTrace();         } catch (IOException due east)         {             e.printStackTrace();         }      } }

8. Using Guava CharStreams

Allow's at present look at the way to convert InputStream to String using Guava Library. Guava is the Google core libraries for Java.

In order to use the Guava library, we demand to add together the beneath dependency

<dependency>
     <groupId>com.google.guava</groupId>
     <artifactId>guava</artifactId>
     <version>27.i-jre</version>
</dependency>

CharStreams course proides utility methods for working with character streams. The toString() method of CharStreams course, reads all characters from a Readable object into a Cord. We demand to pass inputStreamReader instance and Charset to the toString().

package com.javainterviewpoint;  import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets;  import com.google.common.io.CharStreams;  public class InputStreamToString {     public static void main(String[] args)     {         InputStream inputStream = null;         try         {             inputStream = new FileInputStream (new File("D:\\temp.txt"));                          Cord result = CharStreams.toString(new InputStreamReader(                     inputStream, StandardCharsets.UTF_8));                           System.out.println(result);         } catch (FileNotFoundException eastward)         {             e.printStackTrace();         } take hold of (IOException e)         {             e.printStackTrace();         }      } }

9. Using Guava ByteSource

  • ByteSource class is an immutable supplier of InputStream instances. The openStream() method opens a new InputStream for reading from this source.
  • We will be overriding the openStream() method to employ the inputStream which we take created to read the input file.
  • Now view ByteSource equally a CharSource with a UTF8 charset using the asCharSource() method.
  • Use the read() method to read the CharSource as String.
package com.javainterviewpoint;  import java.io.File; import coffee.io.FileInputStream; import coffee.io.FileNotFoundException; import java.io.IOException; import coffee.io.InputStream; import coffee.nio.charset.StandardCharsets;  import com.google.mutual.io.ByteSource;  public form InputStreamToString {     public static void main(Cord[] args)     {         endeavour         {             InputStream inputStream = new FileInputStream (new File("D:\\temp.txt"));                          ByteSource byteSource = new ByteSource() {                 @Override                 public InputStream openStream() throws IOException {                     return inputStream;                 }             };                       String result = byteSource.asCharSource(StandardCharsets.UTF_8).read();                          Arrangement.out.println(result);                      } catch (FileNotFoundException e)         {             e.printStackTrace();         } catch (IOException e)         {             e.printStackTrace();         }      } }

Happy Learning !! 🙂

Practise let me know if yous come across any new methodology to convert InputStream to Cord.

kirbyfeativill.blogspot.com

Source: https://www.javainterviewpoint.com/convert-inputstream-to-string-in-java/

0 Response to "Java 8 Read All Bytes From Inputstream and Returns String"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel