Several ways in which Java transforms InputStream into String

Source: Internet
Author: User
Tags google guava

In Java, we often encounter the case of how to convert InputStream to string, such as getting a inputstream from a file or a network, which needs to be converted into a string output or assigned to another variable.

The way I used to do this before really focusing on this problem was to read the buffer in bytes over and over, or to set up BufferedReader read-by-line. In fact, there is no need to bother, we can use Apache Commons ioutils, or JDK 1.5 after the Scanner, also can be used Google Guava library charstreams. To JDK7, you can also use the Java.nio.file.files#readalllines and Java.nio.file.files#readallbytes methods to get a string directly from a file.

Here's a look at each example, in order to be able to actually use the operation, an example is written in the main method, and a inputstream is obtained from the file, and the code throws out the exceptions that might be caught. And then pay attention to processing input and output stream when there is a character set, the character set is garbled, the default character set is System.getproperty ("file.encoding"), usually we use UTF-8, exception Unsupportedencodingexception inherits from IOException.

1. Using the Scanner of JDK 5

Package Cc.unmi.test;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.inputstream;import Java.util.scanner;public class Test {    /**     * @param args     * @throws FileNotFoundException      *    /public static void main (string[] args) throws FileNotFoundException {        InputStream InputStream = new FileInputStream ("D:/sample.txt");        Scanner Scanner = new Scanner (InputStream, "UTF-8");        String Text = Scanner.usedelimiter ("\\a"). Next ();        System.out.println (text);        Scanner.close ();    }}

2. JDK1.4 and previous BufferedReader law

 Packagecc.unmi.test;ImportJava.io.BufferedReader;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader; Public classTest {/**     * @paramargs *@throwsIOException*/     Public Static voidMain (string[] args)throwsIOException {inputstream InputStream=NewFileInputStream ("D:/sample.txt"); StringBuilder StringBuilder=NewStringBuilder (); BufferedReader BufferedReader=NewBufferedReader (NewInputStreamReader (InputStream),, "UTF8"); BooleanFirstline =true; String Line=NULL;  while(line = Bufferedreader.readline ())! =NULL)        {          if(!firstline) {Stringbuilder.append (System.getproperty ("Line.separator")); }         Else{firstline=false;          } stringbuilder.append (line);         } System.out.println (Stringbuilder.tostring ()); } }

The middle of those judgments is not the first line to decide whether to add a newline character

JDK1.4 and the previous Readbytes method

Package Cc.unmi.test;import Java.io.fileinputstream;import Java.io.ioexception;import java.io.InputStream;public Class Test {    /**     * @throws ioexception      *    /public static void main (string[] args) throws IOException {
   
    inputstream InputStream = new FileInputStream ("D:/sample.txt");                byte[] buffer = new byte[2048];        int readbytes = 0;        StringBuilder StringBuilder = new StringBuilder ();        while ((readbytes = inputstream.read (buffer)) > 0) {            stringbuilder.append (new String (buffer, 0, readbytes));        }                System.out.println (stringbuilder.tostring ());}    }
   

The size of the buffer itself according to the actual tune, more concise than the BufferedReader, do not need to tube line-break things.

4. Apache Commons Ioutils.tostring method

 Packagecc.unmi.test;ImportJava.io.*;Importorg.apache.commons.io.IOUtils; Public classTest {/**     * @throwsioexception Introduction of Apache IO package*/  Public Static voidMain (string[] args)throwsIOException {inputstream InputStream=NewFileInputStream ("D:/sample.txt"); String text= Ioutils.tostring (InputStream, "UTF-8");    System.out.println (text); } }

Third-party library is a third-party library, people take full account of your feelings, your JDK library complaints, more concise, a line to fix. Ioutils can also copy the contents into other writers, such as Ioutils.copy (InputStream, New StringWriter ()).

5. Google Guava's Charstreams method

Package Cc.unmi.test;import Java.io.*;import Com.google.common.io.charstreams;public class Test {    /**     * @ Throws IOException      *    /public static void main (string[] args) throws IOException {        InputStream InputStream = n EW FileInputStream ("D:/sample.txt");        String Text = charstreams.tostring (new InputStreamReader (InputStream, "UTF-8"));        System.out.println (text);}    }

Charsteams is not directly on the Inputsteam, but also depends on the InputStreamReader arch a bridge.

The NIO readallbytes method of 6.JDK 7

Package Cc.unmi.test;import Java.io.ioexception;import java.nio.file.*;p ublic class Test {    /**     * @throws IOException      *    /public static void main (string[] args) throws IOException {        byte[] bytes = Files.readallbytes (Paths.get ("D:/sample.txt"));        String text = new string (bytes);        System.out.println (text);}    }

7. Using the Bytearrayoutputstream method

InputStream InputStream = new FileInputStream ("./outfile");            Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();            int i =-1;            while ((i = Inputstream.read ())! =-1) {                baos.write (i);            }            System.out.println (Baos.tostring ());

8.the NIO readallbytes of JDK 7

byte [] bytes = Files.readallbytes (Paths.get ("D:/sample.txt"));         New String (bytes);        System.out.println (text);

See a deep understanding of Java character types for garbled characters (repost)

 

Several ways in which Java transforms InputStream into String

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.