一、inputstream轉map
1、將inputstream轉為byte數組
public byte[] inputStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
2、將byte數組轉為map
public Map byteArrayToMap(byte[] byteArr) throws IOException, ClassNotFoundException {
ByteArrayInputStream bis = new ByteArrayInputStream(byteArr);
ObjectInputStream ois = new ObjectInputStream(bis);
Map map = (Map) ois.readObject();
ois.close();
bis.close();
return map;
}
3、整合成inputstream轉map的方法
public Map inputStreamToMap(InputStream is) throws IOException, ClassNotFoundException {
byte[] byteArr = inputStreamToByteArray(is);
return byteArrayToMap(byteArr);
}
二、inputstream讀取
1、逐字節讀取
public String readInputStreamByByte(InputStream is) throws IOException {
byte[] buffer = new byte[1024];
StringBuilder stringBuilder = new StringBuilder();
while (is.read(buffer) != -1) {
stringBuilder.append(new String(buffer, StandardCharsets.UTF_8));
}
return stringBuilder.toString();
}
2、逐行讀取
public String readInputStreamByLine(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close();
return stringBuilder.toString();
}
三、Inputstream轉file
1、inputstream轉file的方法
public void inputStreamToFile(InputStream is, File file) throws IOException {
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
os.flush();
os.close();
is.close();
}
四、InputStream轉FileInputStream
1、將InputStream直接轉為FileInputStream
FileInputStream inputStream = new FileInputStream(inputStreamToString(inputStream));
五、inputstream作用
1、具體作用:
InputStream是Java IO的一個輸入流接口。該接口主要用於從數據源(如文件、網絡、內存緩衝區等)中讀取字節數據。
2、優點:
可以實現高速讀取大量字節數據,適用於網絡傳輸、文件讀取等場景。
3、缺點:
只能讀取字節數據,不能進行任何操作。
六、inputstream是什麼流
1、inputstream是一種字節流,用於讀取輸入的二進制數據。
2、inputstream是Java IO的輸入流接口,用於讀取數據源(如文件、網絡、內存緩衝區等)中的字節數據。
七、Android InputStream
1、Android InputStream已經集成了Java IO中InputStream的所有方法,因此可以使用Java IO中的方法來操作Android InputStream。
八、InputStream屬於接口
1、InputStream屬於Java IO中的接口,接口是一種規範,可以讓類進行實現,從而實現規範中定義的方法。
九、InputStream的直接子類
1、InputStream的直接子類有:FileInputStream、ByteArrayInputStream、PipedInputStream、StringBufferInputStream。這些子類都是將其他類型的輸入數據轉化為字節流。
2、最常用的是FileInputStream,該類是從文件中讀取數據的輸入流,其他的子類不太常用。
以上就是關於Java中inputstream轉string的詳細闡述,涵蓋了多個方面的內容。我們可以根據自己的實際需求,選擇最適合的方法進行操作。
原創文章,作者:WJQN,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/135554.html
微信掃一掃
支付寶掃一掃