在 Java 中将输入流转换为字符串

原文:https://www.studytonight.com/java-examples/convert-inputstream-to-string-in-java

InputStream类是 java.io 包的一部分,代表一个有序的数据序列。InputStreams用于有序地从文件中读取数据。在本教程中,我们将学习将输入流转换为字符串的不同方法。

使用InputStreamReader

InputStreamReader类提供了一种方便的read()方法,将输入流中的数据读入字符数组。然后,我们可以将这个字符数组转换成字符串。

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Demo
{
    public static String inputStreamToString(InputStream i) throws IOException
    {
        InputStreamReader isr = new InputStreamReader(i);
        char[] charArr = new char[256];
        isr.read(charArr);
        return new String(charArr);
    }    
    public static void main(String[] args)
    {
        try
        {
            InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
            String strFromInputStream = inputStreamToString(i);
            System.out.print("String from the Input Stream is: " + strFromInputStream);    
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

来自输入流的字符串是:hello world

在字符串生成器中使用InputStreamReaderBufferedReader

我们可以用BufferedReader来包裹InputStreamReader。它提高了我们项目的整体效率。我们将使用BufferedReaderreadLine()方法,并将这些行存储在一个 StringBuilder 对象中。最后,我们可以使用StringBuilder上的toString()方法来获取字符串。

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Demo
{
    public static String inputStreamToString(InputStream i) throws IOException
    {
        StringBuilder builder = new StringBuilder();
        InputStreamReader isr = new InputStreamReader(i);
        BufferedReader br = new BufferedReader(isr);//Wrapping InputStreamReader with BufferedReader        
        String s;
        while((s = br.readLine()) != null)
            builder.append(s);

        return builder.toString();
    }    
    public static void main(String[] args)
    {
        try
        {
            InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
            String strFromInputStream = inputStreamToString(i);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

来自输入流的字符串是:hello world

在没有字符串生成器的情况下使用InputStreamReaderBufferedReader

我们可以使用BufferedReaderlines()方法简化上一节写的代码。我们不需要使用任何循环或将字符串存储在 StringBuilder 中。

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public class Demo
{
    public static String inputStreamToString(InputStream i)
    {
        InputStreamReader isr = new InputStreamReader(i);
        BufferedReader br = new BufferedReader(isr);
        String s = br.lines().collect(Collectors.joining("\n"));
        return s;
    }
    public static void main(String[] args)
    {
        InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
        String strFromInputStream = inputStreamToString(i);
        System.out.print("String from the Input Stream is: " + strFromInputStream);

    }
}

来自输入流的字符串是:hello world

使用输入流的 readAllBytes()方法

InputStream班在Java 9介绍了readAllBytes()法。我们可以使用这个方法在一行代码中将输入流转换成字符串。但是,不建议使用这种方法来读取具有大量数据的流。

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Demo
{
    public static String inputStreamToString(InputStream i) throws IOException
    {
        return new String(i.readAllBytes());
    }    
    public static void main(String[] args)
    {
        try
        {
            InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
            String strFromInputStream = inputStreamToString(i);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

来自输入流的字符串是:hello world

使用扫描仪类

Scanner是一个众所周知的用于读取和解析数据的类。我们可以使用这个类将输入流转换成字符串。我们将使用hasNext()方法检查数据是否存在,使用nextLine()方法将数据流中的数据读入StringBuilder

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class Demo
{
    public static String inputStreamToString(InputStream i) throws IOException
    {
        Scanner scanner = new Scanner(i);
        StringBuilder builder = new StringBuilder();
        while(scanner.hasNext())
            builder.append(scanner.nextLine());
        return builder.toString();
    }    
    public static void main(String[] args)
    {
        try
        {
            InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
            String strFromInputStream = inputStreamToString(i);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

来自输入流的字符串是:hello world

使用字节数组输出流

我们将使用read()方法从InputStream读取数据,并将其写入字节数组。此 read()方法返回字节数组中写入的字节数(如果没有写入数据,则返回-1)。然后,我们将使用这个字节数组将数据写入ByteArrayOutputStream。最后,我们将使用 toString()方法来获取字符串表示形式。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Demo
{
    public static String inputStreamToString(InputStream i) throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[128];
        int length;
        while((length = i.read(buffer)) != -1)
            baos.write(buffer, 0, length);
        return baos.toString();
    }    
    public static void main(String[] args)
    {
        try
        {
            InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
            String strFromInputStream = inputStreamToString(i);
            System.out.print("String from the Input Stream is: " + strFromInputStream);    
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

来自输入流的字符串是:hello world

使用 java.nio Package

我们可以使用java.nio创建一个新的临时文件,并将输入流中的数据复制到这个文件中。然后,我们可以将这个临时文件的内容读入一个字符串。请注意,当程序结束时,临时文件将被自动删除。

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;

public class Demo
{
    public static String inputStreamToString(InputStream i) throws IOException
    {
        Path file = Files.createTempFile(null, null);
        Files.copy(i, file, StandardCopyOption.REPLACE_EXISTING);
        return new String(Files.readAllBytes(file));

    }

    public static void main(String[] args)
    {
        try
        {
            InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
            String strFromInputStream = inputStreamToString(i);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

来自输入流的字符串是:hello world

使用谷歌番石榴图书馆

我们可以使用番石榴库的CharStreams类将输入流转换成字符串。我们将使用这个类的 toString()方法来实现这一点。它将获取一个可读的对象(像 InputStreamReader),并将数据从其中读入一个字符串。

package snippet;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.google.common.io.CharStreams;

public class Demo
{
    public static String inputStreamToString(InputStream i) throws IOException
    {
        try(InputStreamReader isr = new InputStreamReader(i))
        {
            return CharStreams.toString(isr);
        }
    }

    public static void main(String[] args)
    {
        try
        {
            InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
            String strFromInputStream = inputStreamToString(i);
            System.out.print("String from the Input Stream is: " + strFromInputStream);

        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

来自输入流的字符串是:hello world

使用 Apache Commons IO

org.apache.commons.io包的IOUtils类还包含一个 toString()方法。我们可以直接把 InputStream 对象传递给这个方法,它会把其中的数据读入一个字符串。我们还需要指定一个字符集。

package snippet;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;

public class Demo
{    
    public static void main(String[] args)
    {
        try
        {
            InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream
            String strFromInputStream = IOUtils.toString(i, StandardCharsets.UTF_8.name());
            System.out.print("String from the Input Stream is: " + strFromInputStream);

        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

来自输入流的字符串是:hello world

我们还可以使用 java.io 包的 StringWriter 类,并将 InputStream 的内容复制到 StringWriter 中。我们将使用 IOUtils 类的 copy()方法。

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;

public class Demo
{    
    public static void main(String[] args)
    {
        try
        {
            InputStream i = new ByteArrayInputStream("hello world".getBytes());//Creating the input stream

            StringWriter sw = new StringWriter();
            IOUtils.copy(i, sw, StandardCharsets.UTF_8.name());
            String strFromInputStream = sw.toString();
            System.out.print("String from the Input Stream is: " + strFromInputStream);

        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

来自输入流的字符串是:hello world

摘要

在本教程中,我们学习了将输入流转换为字符串的不同方法。ByteArrayOutputStream高效地执行转换,是推荐的方法。我们可以使用 InputStream 类本身的readAllBytes()方法,但不建议大量使用。

InputStreamReader也不被看好,因为它相当慢,一次只能读取一个字符。我们也可以使用外部库,如番石榴或阿帕奇通用 IO。我们还需要正确处理异常并关闭 InputStream 以避免资源泄漏。