Search code examples
javafiletext-filesfilewriterbufferedwriter

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


I want to know why my code doesn't write to a text file, JVM doesn't throw any 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); 
    }
}

Solution

  • Try calling bw.flush() after writing the data and then you have to close the stream with bw.close() after flushing.

    When closing the BufferedWriter it would be best to put the close statement into a finally block to ensure that the stream is closed, no matter what.

    You should also look into using a try with resource. This makes use of the AutoCloseable feature of BufferedWriter as follows:

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("path/to/file")))) {
         // Do something with writer      
    } catch (IOException e) {
         e.printStackTrace();
    }
    

    That way java will make sure that the stream is closed for you when leaving the try body, no matter what happens.