记录一次流相关故障
记录一次流相关故障
1、项目中有个JSON字典文件,通过流的方式加载进来,写了个输入流转字符串的方法,idea开发环境下运行一切正常,打成jar或者war包运行时,只能加载出部分数据,一开始怀疑过运行内存分配过小、前后端数据传递时大小限制…。
通过逐步排查,找到了问题的根源,转换方法有问题。
/**
* 方法一(弃用)
* 处理输入流,转成字符串
* 这种写法有问题,is.available()不可靠,获取的文件可能被截断
*
* @param is
* @return
*/
@Deprecated
private static String getTextFromInputStream(InputStream is) {
String s = "";
try {
byte[] bytes = new byte[is.available()];
is.read(bytes);
s = new String(bytes, "utf-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s;
}
/**
* 方法二
* 处理输入流,转成字符串
* 使用缓冲区,先写入到ByteArrayOutputStream
*
* @return
*/
private static String handleStream(InputStream is) {
String s = "";
ByteArrayOutputStream output = null;
try {
output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
byte[] result = output.toByteArray();
s = new String(result, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return s;
}
小尾巴~~
只要有积累,就会有进步
原文地址:https://blog.csdn.net/weixin_42831477/article/details/136928338
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!