【问题标题】:How to write ArrayList data to text file in java如何在java中将ArrayList数据写入文本文件
【发布时间】:2016-10-22 05:33:03
【问题描述】:

我正在尝试使用此代码将 ArrayList 数据写入文本文件:

 public PrintWriter w() {
        try {
            FileWriter f = new FileWriter("C:\\Users\\jon\\Desktop\\a.txt");
            PrintWriter br = new PrintWriter(f);

            return br;

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }

        return null;
    }

for (String g : a) {
  try {
    PrintWriter br = w();
    br.println(g);
    System.out.print(" " + g);
  } catch (Exception e1) {
    JOptionPane.showMessageDialog(null, e1);
  }

但它没有将数据写入文本文件。谁能帮我看看问题?

【问题讨论】:

  • 您可以将其转换为JSON,然后将其写入文本文件。
  • 你遇到了什么异常?
  • @SachinMesare 如何转换请解释一下。

标签: java arraylist printwriter


【解决方案1】:

这里是:

public static BufferedWriter w() throws IOException{
         File file = new File("D:\\filename.txt");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);

        return bw;

        }

这就是您需要从 for 循环中调用的内容:

for (String g : a) {
    try {

            BufferedWriter bw = w();

            bw.write(g);
            bw.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 2021-03-07
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多