在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);
}
}
}