目前我有以下代码用于阅读InputStream
. 我将整个文件存储到一个StringBuilder
变量中,然后处理这个字符串。
public static String getContentFromInputStream(InputStream inputStream)
// public static String getContentFromInputStream(InputStream inputStream,
// int maxLineSize, int maxFileSize)
{
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String lineSeparator = System.getProperty("line.separator");
String fileLine;
boolean firstLine = true;
try {
// Expect some function which checks for line size limit.
// eg: reading character by character to an char array and checking for
// linesize in a loop until line feed is encountered.
// if max line size limit is passed then throw an exception
// if a line feed is encountered append the char array to a StringBuilder
// after appending check the size of the StringBuilder
// if file size exceeds the max file limit then throw an exception
fileLine = bufferedReader.readLine();
while (fileLine != null) {
if (!firstLine) stringBuilder.append(lineSeparator);
stringBuilder.append(fileLine);
fileLine = bufferedReader.readLine();
firstLine = false;
}
} catch (IOException e) {
//TODO : throw or handle the exception
}
//TODO : close the stream
return stringBuilder.toString();
}
该代码已与安全团队进行审查,并收到以下评论:
BufferedReader.readLine
容易受到 DOS(拒绝服务)攻击(无限长的行,不包含换行/回车的大文件)变量的资源耗尽
StringBuilder
(文件包含的数据大于可用内存的情况)
以下是我能想到的解决方案:
readLine
创建方法 ( )的替代实现readLine(int limit)
,它检查否。读取的字节数,如果超过指定的限制,则抛出自定义异常。逐行处理文件而不加载整个文件。(纯非Java解决方案:))
请建议是否有任何现有的库可以实现上述解决方案。还建议提供比提议的解决方案更稳健或更便于实施的任何替代解决方案。尽管性能也是一项主要要求,但安全性是第一位的。