一、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/zh-hant/n/290790.html
微信掃一掃
支付寶掃一掃