java中如何将二进制文件的InputStream写入String
要将二进制文件的InputStream写入String,可以使用Java的IO流操作。
以下是一种常见的方法:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
try {
InputStream inputStream = Main.class.getResourceAsStream("binaryFile.bin");
String binaryString = convertInputStreamToString(inputStream);
System.out.println(binaryString);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString("UTF-8"); // 指定字符编码
}
}
在上面的代码中,convertInputStreamToString方法接收一个InputStream作为参数,并使用ByteArrayOutputStream来读取InputStream中的数据。然后使用指定的字符编码将字节数组转换为String,并返回该String。
注意:在上述代码中,Main.class.getResourceAsStream("binaryFile.bin")是获取二进制文件的InputStream的方式,需要根据实际情况进行修改
原文地址: http://www.cveoy.top/t/topic/hQSt 著作权归作者所有。请勿转载和采集!