为什么我的代码不写入文本文件?

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

我想知道为什么我的代码不写入文本文件,JVM 不抛出任何异常...

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

您应该为 BufferedWriter 实例调用 closeflush 以便将数据刷新到文件中。无论如何,关闭您正在使用的任何资源总是很重要的。

尝试在写入数据后调用 bw.flush(),然后您必须在刷新后使用 bw.close() 关闭流。

关闭 BufferedWriter 时,最好将 close 语句放入 finally 块中,以确保无论如何关闭流。

您还应该考虑使用 try with resource。这利用了 BufferedWriterAutoCloseable 特性,如下所示:

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

这样 java 将确保在离开 try 主体时为您关闭流,无论发生什么情况。

您需要确保,我们需要 flush() 将更改推送到文件, 还要确保您正在关闭文件资源:

public void writeToFile(Data[] rawData){
        BufferedWriter bw = null;
        try{    
        fw = new FileWriter(informationFile);
        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();
        } finally {
               if(fw  != null) {
                     fw.close();
                     fw = null;
               }
               if(bw  != null) {
                     bw.close();
                     bw = null;
               }
        }
    }