【问题标题】:How can I abort a request if the XML file is too large?如果 XML 文件太大,如何中止请求?
【发布时间】:2014-02-24 00:23:57
【问题描述】:

在我的 servlet 中,我目前正在将 XML 文件设置为这样的变量:

String xmlFileAsString = CharStreams.toString(new   
         InputStreamReader(request.getInputStream(), "UTF-8"));

现在在这一行之后我可以检查文件是否太大等,但这意味着整个文件已经被流式传输并加载到内存中。

有没有办法让我获得输入流,但是当这是流式传输文件时,如果文件大小超过 10MB,它应该中止?

【问题讨论】:

  • 如果我没记错的话,听起来你只想使用request.getInputStream().read(someBuffer, 0, 1028 * 1028 * 10)。之后就是将字节数组转换为字符串的问题。

标签: java spring spring-mvc jetty inputstream


【解决方案1】:

您可以按顺序读取流并计算读取的字符数。首先不要使用CharStreams,因为它已经读取了整个文件。创建一个InputStreamReader 对象:

InputStreamReader reader;
        reader = new InputStreamReader(request.getInputStream(), "UTF-8");

用于跟踪字符数的变量:

long charCount = 0;

然后是读取文件的代码:

char[] cbuf = new char[10240]; // size of the read buffer
int charsRead = reader.read(cbuf); // read first set of chars
StringBuilder buffer = new StringBuilder(); // accumulate the data read here

while(charsRead > 0) {
    buffer.append(cbuf, 0, charsRead);
    if (charCount > LIMIT) { // define a LIMIT constant with your size limit
        throw new XMLTooLargeException(); // treat the problem with an exception
    }
}
String xmlFileAsString = buffer.toString(); //if not too large, get the string

【讨论】:

  • 我想较小的 cbuf 更好,b/c 目前它会在存在 b/c 超出限制之前读取两倍的数量。如果你把 cbuf 设为 1024 会不会更慢?
  • 我认为 1024 是一个不错的尺寸,不会造成任何重大影响。您还可以使用 new StringBuilder(cbuf.length) 来提高使用缓冲区大小初始化 StringBuilder 的性能。
  • 哦,现在我看到我输入了 10240。我的意思是 1024。我通常使用 4096 和 8192 之类的块大小。但是 1024 也很好,特别是如果你有可变数据大小。
猜你喜欢
  • 2019-12-20
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多