gpt4 book ai didi

java - BufferedWriter 不写入文件

转载 作者:行者123 更新时间:2023-11-29 07:51:39 25 4
gpt4 key购买 nike

我正在制作一个程序,我需要将一个随机 6 位数 ID 列表添加到一个文件中。目前,每当我运行程序的这一部分时,文件中都不会添加任何内容。我到底做错了什么,以至于代码没有写入文件?我检查并确保确实生成了所有随机数。

static HashSet<Integer> idHashList = 
new HashSet<>();

public static void createIds(){
File writeId = new File("peopleIDs.txt");
try {
FileWriter fw = new FileWriter(writeId,true);
BufferedWriter out = new BufferedWriter(fw);

for(int i = 0; i < 100; i++){
out.write(People.genRand());
}
out.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}

protected static int genRand(){
while(true){
int rand = ((int) ((Math.random() * (899999))+100000));
if(idHashList.add(rand)){
return rand;
}
}
}

最佳答案

它可能会写入一个文件,但不是您认为的那个。 Java 将写入当前目录中的 peopleIDs.txt 文件。当前目录是执行 java 命令的目录。

如果您从 IDE 启动程序,请检查运行配置以查看它使用的当前目录。如果你真的不知道,那就在你的硬盘上搜索 peopleIDs.txt 来找出答案。

也就是说,close() 应该在 finally block 中。或者更好的是,您应该使用 try-with-resources构造。

关于java - BufferedWriter 不写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20693270/

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