一、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/n/135554.html
微信扫一扫
支付宝扫一扫