java 如何inputstream
使用 InputStream 读取数据
在 Java 中,InputStream 是一个抽象类,用于从不同数据源(如文件、网络、内存等)读取字节数据。以下是几种常见的 InputStream 使用方法。
从文件读取数据
使用 FileInputStream 读取文件内容:
try (InputStream inputStream = new FileInputStream("example.txt")) {
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
使用缓冲读取提高效率
BufferedInputStream 可以提高读取效率:
try (InputStream inputStream = new BufferedInputStream(new FileInputStream("example.txt"))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
从字节数组读取数据
ByteArrayInputStream 可以从字节数组读取数据:
byte[] data = "Hello, World!".getBytes();
try (InputStream inputStream = new ByteArrayInputStream(data)) {
int byteData;
while ((byteData = inputStream.read()) != -1) {
System.out.print((char) byteData);
}
} catch (IOException e) {
e.printStackTrace();
}
读取网络数据
使用 URL.openStream() 获取网络资源的 InputStream:
try (InputStream inputStream = new URL("https://example.com").openStream()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用 try-with-resources 自动关闭流
Java 7 引入的 try-with-resources 语法可以自动关闭 InputStream,无需手动调用 close():
try (InputStream inputStream = new FileInputStream("example.txt")) {
// 使用 inputStream
} catch (IOException e) {
e.printStackTrace();
}
转换为其他数据格式
将 InputStream 转换为字符串:

try (InputStream inputStream = new FileInputStream("example.txt")) {
String content = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
注意事项
- 使用
InputStream后必须关闭资源,避免内存泄漏。 - 处理大文件时建议使用缓冲(如
BufferedInputStream)以提高性能。 - 检查
read()返回值是否为-1,表示流结束。 - 指定字符编码(如
StandardCharsets.UTF_8)以避免乱码问题。






