【问题标题】:Why doesn't my code write to a text file?为什么我的代码不写入文本文件?
【发布时间】:2015-09-21 07:14:37
【问题描述】:

我想知道为什么我的代码没有写入文本文件,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); 
    }
}

【问题讨论】:

标签: java file text-files filewriter bufferedwriter


【解决方案1】:

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

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

您还应该考虑使用资源尝试。这利用了BufferedWriterAutoCloseable 功能,如下所示:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您需要确保,我们需要 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;
                     }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2013-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 2019-11-09
        • 1970-01-01
        • 2021-01-20
        • 2019-08-01
        相关资源
        最近更新 更多