Java 如何获取 InputStream 流中的数据并打印出来

在Java中,InputStream 是一个抽象类,用于表示从输入源读取字节流,如何打印出来 InputStream 里面的内容有以下几种方法。

一、使用 BufferedReader(适用于文本数据)

如果 InputStream 包含的是文本数据(例如UTF-8编码的字符串),可以使用 BufferedReader 来逐行读取。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class InputStreamExample {
    public static void main(String[] args) {
        // 假设你已经有一个 InputStream 对象
        InputStream inputStream = ...;
        StringBuilder builder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
            	builder.append(line).appeng('\n');
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (builder.length() > 0 && builder.charAt(builder.length() - 1) == '\n') {
        	// 判断去掉最后一个换行符
        	builder.setLength(builder.length() - 1);
        }
        System.out.println(builder);
    }
}

二、使用 byte 数组(适用于二进制数据)

如果 InputStream 包含的是二进制数据,可以直接读取到一个字节数组中。

import java.io.InputStream;
import java.io.IOException;

public class InputStreamExample {
    public static void main(String[] args) {
        // 假设你已经有一个 InputStream 对象
        InputStream inputStream = ...;
        try {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                // 处理读取到的数据
                System.out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) inputStream.close();
            } catch (IOException ex) { /* 忽略 */ }
        }
    }
}

三、使用 Files.copy 方法(适用于将输入流的内容复制到文件或输出流)

如果你需要将 InputStream 的内容复制到文件或另一个输出流中,可以使用 Files.copy 方法。

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class InputStreamExample {
    public static void main(String[] args) throws IOException {
        // 假设你已经有一个 InputStream 对象
        InputStream inputStream = ...;
        Path targetPath = Paths.get("target-file.txt");
        Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
        // 关闭资源
         if (inputStream != null) inputStream.close();
    }
}

四、使用 Apache Commons IO 库(简化操作)

Apache Commons IO 提供了一些方便的方法来处理 I/O 操作。例如,可以使用 IOUtils.toString() 或 IOUtils.toByteArray() 等方法直接将整个输入流转换为字符串或字节数组。

首先添加依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>
import org.apache.commons.io.IOUtils;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class InputStreamExampleWithCommonsIO {
    public static void main(String[] args){
       // 假设你已经有一个 InputStream 对象 
       InputStream inputStream = ...; 
       try{
           String contentAsString = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
           System.out.println(contentAsString);
           byte[] contentAsBytesArray = IOUtils.toByteArray(inputStream);
           System.out.println(new String(contentAsBytesArray));
       }catch(IOException ex){
          ex.printStackTrace(); 
       }finally{
          IOUtils.closeQuietly(inputStream); 
       }
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值