gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:11:26 26 4
gpt4 key购买 nike

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

最佳答案

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

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

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

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

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

关于java - 为什么我的代码不写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32689346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com