I am trying to write a program that emulates a database by writing to a text file. I can read a text file full of data to use and then convert it to a byte array to store into another text file. The issue I’m having is as I’m converting from a string to a byte array I keep getting the java.lang.ArrayIndexOutOfBoundsException: 8. I hard coded values into my for loops so that it shouldn’t be an invalid index for the array but nothing seems to fix the problem. Here is my function that the error shows up in:
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());
}
}
I put the loop in a try/catch thinking that it would still at least output the bytes to my text file and then not add any more to the file once it hits an invalid index, but that’s not the case. I’m mainly having trouble figuring out why I keep getting this error. I can print out the array no problem and everything shows up if I don’t try to write it to the text file.
Any help is appreciated!
This is the problem:
Look at the loop initialization and the loop condition, both of which use
j– then look at the increment, which is changing the value ofz.Even the commented out version is still broken, as it’s still incrementing
z.In fact, you don’t need
jat all as far as I can see. You can change your inner loop to:However, I would strongly encourage you not to call
getBytes()without an encoding in the first place. If you really want the default platform encoding, specify that explicitly. If you want some other encoding such as UTF-8, specify that. If you don’t know what encoding you want, you need to take a step back and think carefully about your data.(It’s also slightly odd that you’re calling
writeSectorwith the same value ofzeach time… isn’t that going to just overwrite the data?)