Java servlet,从文件读取,数组越界

标签 java string servlets

我正在制作一个java servlet,我的任务是获取文件中写入的产品的总成本:

category1 1 10 101 1 good1
category6 2 11 105 2 good5
category1 5 13 103 3 good4
category3 6 14 102 4 good2
category5 3 12 107 2 good1

费用在第 4 栏。我已经写了:

    public int Sum_of_Elements()throws IOException{
    int sum = 0;
    BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
    String line = "";
    while((line=br.readLine())!=null){
        String[] columns = line.split(" ");
        sum = sum + Integer.parseInt(columns[4]);
    }
    System.out.println(sum);
    return sum;
}

而且它不起作用。当我进入 servlet 页面时,我得到

java.lang.ArrayIndexOutOfBoundsException: 4

怎么了?以及如何修复它?

最佳答案

如果存在以下情况,此代码将失败:文件中的空行,或者格式不同的行,或者空格实际上是制表符(也许还有更多原因)。如果你想进行防御性编程,你应该这样做:

while((line=br.readLine())!=null) {
    String[] columns = line.split(" ");
    if( columns != null && columns.length >= 5 ) {
        sum = sum + Integer.parseInt(columns[4]);
    }
    else {
        // do what you must here; it may be an error to encounter such a line:
        throw new IllegalArgumentException("malformatted line: " + line);
        // or it may be OK to swallow the exceptional case
        // or you may only need to silently log it:
        logger.warn("malformatted line: " + line);
        // etc...
    }
}

关于Java servlet,从文件读取,数组越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20815501/

相关文章:

java - 将迭代器从 JSONObject 重写为 JSONArray

c# - 从 string[] 构建一个字符串而不使用任何循环

c - 查找字符串的长度

java - java servlet 中出现令人惊讶的结果

java - 在某些 <div> 中显示 Servlet 响应

java - Android JSON API 调用

Java - 从应用程序刷新打开的 html 页面

java - 我是否正确使用 Java PooledConnections?

c++ - 为 C++ 字符串中的特殊符号 (") 赋予字面意义的有效 C++ 方法

java - jsp 页面( View )和 servlet( Controller )之间的事务排序