英文:
Saving Arraylist to Text document seperate lines
问题
尝试将ArrayList的项目保存到文本文件中,我有点让它工作了,但它会将整个ArrayList保存在一行中。
我希望每行保存一个项目,并且不要有重复项或在开头的空括号。非常感谢任何帮助。如果可能的话,还请去掉文本周围的括号,以便更容易读入ArrayList。
英文:
Trying to save arraylist items to a text file, I kind of have it working but it saves the whole arraylist on one line
I am hoping to save it per line and not have any duplicates or the empty brackets at the start, Any help would be much appreciated. Also if possible to remove the brackets around the text for easier reading into an arraylist
答案1
得分: 0
你可以迭代地遍历地图,并将所有变量保存在单独的行中。
示例:
private List<Object> objects;
private void example() {
// JDK >= 8
this.objects.forEach(this::writeInFile);
// JDK < 8
for (Object object : this.objects) {
this.writeInFile(object);
}
}
private void writeInFile(Object object) {
// 在这里编写你的代码
}
英文:
You can iterate over the map and save all variables in separate lines.
Example:
private List<Object> objects;
private void example() {
//JDK >= 8
this.objects.forEach(this::writeInFile);
//JDK < 8
for (Object object : this.objects) {
this.writeInFile(object);
}
}
private void writeInFile(Object object) {
//your code here
}
答案2
得分: 0
FileOutputStream适用于当您的数据已经以字节格式存在。我建议您使用类似PrintWriter的东西。
PrintWriter pw = null;
try {
File file = new File("file.txt"); //已编辑
pw = new PrintWriter(file); //已编辑
for(String item: Subreddit_Array_List)
pw.println(item);
} catch (IOException e) {
e.printStackTrace();
}
finally{
pw.close();
}
请记住,这将覆盖之前文件中的内容,而不是追加内容。输出将格式化如下:
Cats
Dogs
Birds
英文:
FileOutputStream is more fitting for when your data is already in a byte format. I suggest you use something like a PrintWriter.
PrintWriter pw = null;
try {
File file = new File("file.txt"); //edited
pw = new PrintWriter(file); //edited
for(String item: Subreddit_Array_List)
pw.println(item);
} catch (IOException e) {
e.printStackTrace();
}
finally{
pw.close();
}
Keep in mind this overwrites what was in the file before rather than appends to it. The output will be formatted like:
Cats
Dogs
Birds
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论