将ArrayList保存到文本文档,每行分开。

huangapple go评论78阅读模式
英文:

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&lt;Object&gt; objects;
  
  private void example() {
    //JDK &gt;= 8
    this.objects.forEach(this::writeInFile);
    //JDK &lt; 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(&quot;file.txt&quot;); //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

huangapple
  • 本文由 发表于 2020年4月6日 21:47:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/61061326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定