如何在java中将ArrayList数据写入文本文件

时间:2016-10-22 05:33:03

标签: java arraylist printwriter

我正在尝试使用以下代码将ArrayList数据写入Text文件:

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

但它没有将数据写入文本文件。任何人都可以帮我看看问题吗?

1 个答案:

答案 0 :(得分:-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();
        }
}