0

I'm trying to write an ArrayList to a file in java. This is what I do in main class:

To write Strings into the ArrayList I do:

list.add(String);

Then, to write it to the file:

readWrite.writing(list);

list is: List<String> list = new ArrayList<String>();

readWrite references to this class where I have defined the methods to read/write to a file:

 public void writing(ArrayList listToWrite) throws IOException {
    fileOutPutStream = new FileOutputStream (file);
    write = new ObjectOutputStream (fileOutPutStream);
    for (int i=0; i<=listToWrite.size(); i++){
        write.writeObject(listToWrite.get(i));
    }
    write.close();
}

When trying it on the console, I'm getting this exception:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at //*I GET REFERENCED TO THIS LINE IN THE CODE ABOVE:* **write.writeObject(listToWrite.get(i));**

3 Answers 3

3

Be careful with your limits: with <= you go one item past the end of the list.

for (int i=0; i<listToWrite.size(); i++){

Then again, note that ArrayList is itself serializable. You could just write it to the file without looping:

write = new ObjectOutputStream(fileOutPutStream);
write.writeObject(listToWrite);
write.close();
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfect! I'll try the suggestion
2

Might be best to just go with:

for (String str : listToWrite){
    // DO WORK HERE
}

That way you don't have to worry about all of that messy indexing business.

Comments

1

Another solution would also be:

BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
outputWriter.write(Arrays.toString(array));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.