1

It seems fine but the the content is not write into file with write() method. I ask the user input with JoptionPane and add that data to ArrayList . The data is added , but when I try to output that data into file, it's not write to file.

public class fileArray {
public static void main(String[] args) throws IOException {
    ArrayList al = new ArrayList();
    File f =new File("notworking.txt");
    String names = " ";



    while(!names.isEmpty())
    {
        names=JOptionPane.showInputDialog("EnterName");
        if(!names.isEmpty()){
        al.add(names);}
    }

    FileWriter fw = new FileWriter(f.getAbsoluteFile());
    BufferedWriter bw  = new BufferedWriter(fw);
    int sz= al.size();
    for(int i =0;i<sz;i++){
    bw.write((String) al.get(i));
        System.out.println(al.get(i));
            }



}

}

3 Answers3

0

You need to close the writer after you are done with writing.

bw.close();
Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52
Henry
  • 42,982
  • 7
  • 68
  • 84
0

Either you have to flush or close the buffer afte you write to the file. Better you close the buffer in finally block, make it habit to close the buffer in finally block.

Dinesh
  • 1,046
  • 1
  • 8
  • 17
0

sample code:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();   // CLOSE