如何处理 Java 中的 ArrayIndexedBoundexception

How to handle ArrayIndexedBoundexception in Java

我一直在尝试从一个 csv 文件中获取特定的列,比如说有 30 列,但是当我执行以下代码时我只需要完全 3 列我只得到一整列数据..如何获得 3 列time.when i 运行 处的数据它只打印一列...当我尝试打印多列时它显示错误消息,如

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at ReadCVS.main(ReadCVS.java:19)

public static void main(String[] args) throws Exception {
    String splitBy = ",";
    BufferedReader br = new BufferedReader(new FileReader("txt.csv"));
    String line = br.readLine();

    while((line = br.readLine()) !=null){
        String[] b = line.split(splitBy);

        PrintWriter out = new PrintWriter(new FileWriter("new.csv",true));

        out.println(b[0]);

        out.close();
    }
    br.close();
}

问题大概是: 您的 txt.csv 文件中只有一行。

当您第一次调用 br.readLine(); 时,将从文件中读取该行并存储在 String line 变量中。但是你忽略了那一行,你又读了一遍,在你的 while 条件下:

while((line = br.readLine()) !=null)

所以第一行之后可能有空行或空字符串。然后 while 条件为真,但行变量中存储了一个空字符串。所以 b[] 没有元素, b[0] 超出范围。

一个解决方案是更改此行:

String line = br.readLine();

String line = null;

[编辑]

因此,如果您尝试读取 mkyong 站点中的文件(如您在评论中链接的那样)并用“,”拆分行并将它们写入新文件,例如,您可以使用代码喜欢下面的代码:

public static void main(String[] args) throws IOException {
    BufferedWriter out = new BufferedWriter(new FileWriter("c:\new.csv",true));
    BufferedReader br = new BufferedReader(new FileReader("c:\txt.csv"));
    String splitBy = ",";
    String line = null;
    while((line = br.readLine()) !=null){
        StringBuffer newLine = new StringBuffer();
        String[] b = line.split(splitBy);
        for (int i = 0; i<b.length; i++)
        {
            if(b[i] == null || b[i].trim().isEmpty())
                continue;

            newLine.append(b[i].trim() + ";");
        }
        out.write(newLine.toString());
        out.newLine();
    }
    out.close();
    br.close();
}

您还应该知道以下行以可追加方式打开输出文件(构造函数中的第二个布尔参数):

BufferedWriter out = new BufferedWriter(new FileWriter("c:\new.csv",true));

我还假设源文件的内容与 mkyong 站点中的相同,如下所示:

"1.0.0.0",,  ,  ,"1.0.0.255","16777216",  , "16777471","AU" ,, "Australia"
"1.0.1.0" ,  ,, "1.0.3.255" ,,   ,"16777472","16778239" , ,  "CN"  ,   ,"China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"

祝你好运。