繁体   English   中英

为什么我的代码没有写到文本文件?

[英]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块中,以确保无论如何都关闭流。

您还应该考虑对资源进行尝试。 这利用了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;
               }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM