-4

I m trying to write ArrayList data in to the Text file using this code:

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

But it is not writing the data to the text file. Can anyone help me see the problem?

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
jon
  • 37
  • 6

1 Answers1

-1

Here it is:

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;

        }

and this is what you need to call from your for loop:

for (String g : a) {
    try {

            BufferedWriter bw = w();

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

            System.out.println("Done");

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