一、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-tw/n/290790.html