InputStream是Java IO非常重要的一部分,被廣泛地使用在各種應用場景中。本文將從多個方面闡述以InputStream為中心的Java開發。
一、InputStream概述
InputStream是一個抽象類,定義了讀取字節流的標準接口。它提供了以下方法:
int read() throws IOException;
int read(byte[] b) throws IOException;
int read(byte[] b, int off, int len) throws IOException;
long skip(long n) throws IOException;
int available() throws IOException;
void close() throws IOException;
void mark(int readlimit);
void reset() throws IOException;
boolean markSupported();
InputStream的子類包括FileInputStream、ByteArrayInputStream、FilterInputStream等。其中,FileInputStream可以從文件中讀取字節流,ByteArrayInputStream可以從字節數組中讀取字節流,FilterInputStream可以過濾其他輸入流並提供其它擴展功能。
二、InputStream使用示例
以下代碼演示了如何使用FileInputStream從文件中讀取字節流:
File file = new File("file.txt");
InputStream inputStream = new FileInputStream(file);
int data = inputStream.read();
while (data != -1) {
System.out.print((char) data);
data = inputStream.read();
}
inputStream.close();
以下代碼演示了如何使用ByteArrayInputStream從字節數組中讀取字節流:
byte[] bytes = "hello world".getBytes();
InputStream inputStream = new ByteArrayInputStream(bytes);
int data = inputStream.read();
while (data != -1) {
System.out.print((char) data);
data = inputStream.read();
}
inputStream.close();
三、InputStream的擴展應用
1. IOUtils
IOUtils是一個由Apache Commons IO庫提供的有用工具類,可以簡化InputStream的使用過程。例如,以下代碼演示了如何使用IOUtils從文件中讀取字節流:
File file = new File("file.txt");
InputStream inputStream = new FileInputStream(file);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
System.out.println(content);
inputStream.close();
以上代碼將文件中的內容讀取成字符串,並使用UTF-8編碼。
2. InputStream讀取流式數據
除了讀取文件和字節數組外,InputStream還可以用於讀取流式數據,例如Web服務返回的數據。
URL url = new URL("https://example.com/");
InputStream inputStream = url.openStream();
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
System.out.println(content);
inputStream.close();
以上代碼將從網站 https://example.com/ 中讀取數據,並將其轉換為字符串。
3. 對InputStream對象進行包裝
通過對InputStream對象進行包裝,我們可以實現各種有用的擴展功能,例如限制讀取流的速度、對數據進行加密等。
public class DecryptInputStream extends FilterInputStream {
public DecryptInputStream(InputStream inputStream) {
super(inputStream);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int n = super.read(b, off, len);
if (n > 0) {
for (int i = off; i < off + n; i++) {
b[i] = decrypt(b[i]);
}
}
return n;
}
private byte decrypt(byte b) {
return (byte) (b - 1);
}
}
File file = new File("file.txt");
InputStream inputStream = new FileInputStream(file);
InputStream decryptedInputStream = new DecryptInputStream(inputStream);
String content = IOUtils.toString(decryptedInputStream, StandardCharsets.UTF_8);
System.out.println(content);
decryptedInputStream.close();
inputStream.close();
以上代碼演示了如何使用FilterInputStream對讀取流進行解密。在DecryptInputStream中,我們重載了read(byte[] b, int off, int len)方法,對每個讀取到的字節進行解密。
四、總結
本文從InputStream的概述、使用示例和擴展應用三個方面,對以InputStream為中心的Java開發進行了詳細闡述。在實際開發過程中,可以靈活運用InputStream及其子類,實現各種有用的功能以滿足應用需求。
原創文章,作者:IQCR,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/132086.html