简体   繁体   English

从ArrayList写入文件

[英]Write to file from ArrayList

I'm trying to write an ArrayList to a file in java. 我正在尝试将ArrayList写入Java中的文件。 This is what I do in main class : 这是我在主班做的事情:

To write Strings into the ArrayList I do: 要将字符串写到ArrayList中,我需要:

list.add(String);

Then, to write it to the file: 然后,将其写入文件:

readWrite.writing(list);

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

readWrite references to this class where I have defined the methods to read/write to a file: readWritereadWrite引用,在该类中,我定义了用于读取/写入文件的方法:

 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));**

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. 再一次,请注意ArrayList本身是可序列化的。 You could just write it to the file without looping: 您可以将其写入文件而无需循环:

write = new ObjectOutputStream(fileOutPutStream);
write.writeObject(listToWrite);
write.close();

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. 这样,您不必担心所有杂乱的索引业务。

Another solution would also be: 另一个解决方案是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM