当前位置: 动力学知识库 > 问答 > 编程问答 >

java - BufferedWriter not writing to file

问题描述:

I am making a program, and I need to add a list of random 6-digit ids to a file. Currently whenever I run this portion of the program, nothing is added to the file. What exactly am I doing wrong so that the code does not write to the file? I checked and made sure that all the random number are definitely being generated.

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;

}

}

}

网友答案:

It probably writes to a file, but not the one you think. Java will write to the peopleIDs.txt file in the current directory. The current directory is the directory from which the java command is executed.

If you launch the program from your IDE, check the run configuration to see which current directory it uses. If you really don't know, then search for peopleIDs.txt on your hard drive to find out.

That said, the close() should be in a finally block. Or even better, you should use the try-with-resources construct.

网友答案:

You're calling the wrong method. BufferedWriter.write(int) only writes a char. Check the Javadoc. If you want to write the integer as four bytes in binary, you need DataOutputStream.writeInt(). If you want to write it as a string, you need BufferedWriter.write(""+People.genRand()), possibly followed by BufferedWriter.newLine().

网友答案:

You can try to fill your file like next:

PrintWriter writer = null;
try {
    writer = new PrintWriter("peopleIDs.txt", "UTF-8");
    for (int i = 0; i < 100; i++) {
        writer.println(genRand());
    }
} catch (IOException ex) {
    System.out.println(ex.getMessage());
} finally {
    if(writer != null){
        writer.close();
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: