bob
bob

Reputation: 135

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;
        }
    }
}

Upvotes: 1

Views: 1936

Answers (3)

user207421
user207421

Reputation: 310884

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().

Upvotes: 1

alex2410
alex2410

Reputation: 10994

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();
    }
}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691685

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.

Upvotes: 4

Related Questions