java - Why doesn't my code write to a text file? -


i want know why code doesn't write text file, jvm doesn't throw exceptions...

public class alterdata {      data[] information;      file informationfile = new file("/users/ramansb/documents/javafiles/information.txt");     filewriter fw;      public void populatedata(){         information = new data[3];          information[0] = new data("big chuckzino", "custom house", 18);         information[1] = new data("rodger penrose", "14 winston lane", 19);         information[2] = new data("jermaine cole", "32 forest hill drive", 30);     }      public void writetofile(data[] rawdata){         try{             fw = new filewriter(informationfile);         bufferedwriter bw = new bufferedwriter(fw);         for(data people : rawdata){              bw.write(people.getname()+ ", ");             bw.write(people.getaddress() + ", ");             bw.write(people.getage() +", |");             }         }catch(ioexception ex){             ex.printstacktrace();         }     }      public static void main(string[] args){             alterdata a1 = new alterdata();             a1.populatedata();             a1.writetofile(a1.information);      } } 

try calling bw.flush() after writing data , have close stream bw.close() after flushing.

when closing bufferedwriter best put close statement block ensure stream closed, no matter what.

you should using try resource. makes use of autocloseable feature of bufferedwriter follows:

try (bufferedwriter writer = new bufferedwriter(new filewriter(new file("path/to/file")))) {      // writer       } catch (ioexception e) {      e.printstacktrace(); } 

that way java make sure stream closed when leaving try body, no matter happens.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -