一、InputStream类介绍
在Java中,使用InputStream类可以方便地读取二进制数据,并将其转化为具体的对象或者基本数据类型。InputStream类是一个抽象类,提供了各种读取二进制数据的方法,如read(byte[] b)、read(byte[] b, int off, int len)等。下面是一段使用InputStream读取文件的示例代码:
try (InputStream inputStream = new FileInputStream("example.txt")) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
// 处理读取到的数据
}
} catch (IOException e) {
e.printStackTrace();
}
以上代码展示了使用try-with-resource语法,在代码块执行完毕后自动关闭InputStream对象。在循环中,每次读取1024字节的数据,并将读取到的字节数保存在变量len中。当读取到文件结束时,InputStream方法的返回值为-1,循环终止。
二、InputStream方法常用操作
InputStream提供了多种方法用于读取二进制数据。下面介绍几种常用的方法:
1. read(byte[] b)
该方法从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中。返回值为读取到的字节数。如果遇到文件结束或者数据不够读,则返回-1。
2. read()
该方法从输入流中读取一个字节并返回。如果遇到文件结束,则返回-1。
3. skip(long n)
该方法跳过输入流中n个字节的数据,并返回实际跳过的字节数。如果n大于输入流中的字节数,则跳过全部数据并返回0。
三、InputStream方法例子
1. 读取文本文件内容并输出
try (InputStream inputStream = new FileInputStream("example.txt")) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len, "UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
}
2. 读取图片文件并输出
try (InputStream inputStream = new FileInputStream("example.png")) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
// 处理读取到的数据
}
// 将二进制数据转化为图片文件
BufferedImage image = ImageIO.read(new ByteArrayInputStream(buffer));
// 显示图片
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.add(label);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
3. 读取网络数据并输出
try (InputStream inputStream = new URL("https://example.com").openStream()) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len, "UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
}
4. 从zip文件中读取数据并输出
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("example.zip"))) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
System.out.println("zip entry name: " + zipEntry.getName());
byte[] buffer = new byte[1024];
int len = -1;
while ((len = zipInputStream.read(buffer)) != -1) {
// 处理读取到的数据
}
}
} catch (IOException e) {
e.printStackTrace();
}
5. 读取socket中的数据并输出
try (Socket socket = new Socket("example.com", 80);
InputStream inputStream = socket.getInputStream()) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len, "UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
}
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/290790.html
微信扫一扫
支付宝扫一扫