如何避免获取java.lang.ArrayIndexOutOfBoundsException

Fra*_* A. -1 java

我正在尝试编写一个通过写入文本文件来模拟数据库的程序.我可以读取一个充满数据的文本文件,然后将其转换为字节数组以存储到另一个文本文件中.我遇到的问题是因为我正在从字符串转换为字节数组我不断得到java.lang.ArrayIndexOutOfBoundsException:8.我将值硬编码到我的for循环中,因此它不应该是无效的索引数组但似乎没有解决问题.这是我的函数,错误显示在:

public void writeBucket(int bucket, String importFile, String[][] allrecords)
{

  theDisk = new FakeDisk();

  for(int z = 0; z < bucket; z++)
  {

    try
     {

      for(int j = 0; j < 7; z++)//for(int j = 0; j < allrecords[z].length; z++)
      {

        if(allrecords[z][j] == null) //this is the line where the error shows up
        {
          continue;
        }

        theDisk.writeSector(z, allrecords[z][j].getBytes());
      }
     }
     catch(Exception e)
     {
         //System.out.println(e.getMessage());//this prints the number 8 when not commented out
       continue;
     }

  }

  try
  {

    FileWriter fwrite = new FileWriter(importFile);

    fwrite.write("\n\n\n\n");
    fwrite.close();

  }
  catch (Exception e)
  {
    System.err.println("Error: " + e.getMessage());
  }

}
Run Code Online (Sandbox Code Playgroud)

我把循环置于try/catch中,认为它仍然至少将字节输出到我的文本文件,然后一旦它到达无效索引就不再添加到文件中,但事实并非如此.我主要是在弄清楚为什么我一直收到这个错误.我可以打印出阵列没问题,如果我不尝试将其写入文本文件,一切都会显示出来.

任何帮助表示赞赏!

Jon*_*eet 5

这就是问题:

for(int j = 0; j < 7; z++)
Run Code Online (Sandbox Code Playgroud)

查看循环初始化和循环条件,两者都使用j- 然后查看增量,即更改值z.

即使是注释掉的版本仍然存在,因为它仍在增加z.

事实上,j就我所见,你根本不需要.您可以将内循环更改为:

for (String text : allrecords[z])
{
    if (text == null)
    {
        continue;
    }
    theDisk.writeSector(z, text.getBytes());
}
Run Code Online (Sandbox Code Playgroud)

但是,我强烈建议您不要在getBytes()没有编码的情况下打电话.如果您确实需要默认平台编码,请明确指定.如果您想要其他编码,例如UTF-8,请指定.如果您不知道自己想要什么编码,则需要退后一步,仔细考虑您的数据.

(你每次writeSector使用相同的值调用也有点奇怪z......是不是只会覆盖数据?)