Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Using BufferedWriter and BufferedReader, [duplicate]

Tags:

java

file

file-io

I am trying to generate random numbers as ids, and save them in a file to easily access them. I am currently using BufferedWriter in order to write these to the file, but the problem is that I am not too sure about how to go about finding where I should start writing into the file. I am currently trying to use BufferedReader to figure out where the next line is to write, but I am not sure how I am supposed to save this offset or anything, or how a new line is represented.

void createIds(){
    File writeId = new File("peopleIDs.txt");
    try {
        FileReader fr = new FileReader(writeId);
        BufferedReader in = new BufferedReader(fr);
        FileWriter fw = new FileWriter(writeId);
        BufferedWriter out = new BufferedWriter(fw);
        String line;
        while((line = in.readLine()) != null){
            //How do I save where the last line of null is?
            continue;
        }
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
}
like image 803
bob Avatar asked Sep 17 '26 15:09

bob


1 Answers

If you simply want to add IDs to the end of the file, use the following FileWriter constructor:

FileWriter fw = new FileWriter(writeId, true);

This opens the FileWriter in append mode, allowing you to write output to a pre-existing file.

If you would like to write the IDs to a particular location within an existing file rather than just to the end, I am not sure if this is possible without first parsing the file's contents.

For more information, see the JavaDoc for FileWriter.

like image 68
x4nd3r Avatar answered Sep 20 '26 04:09

x4nd3r