SüniÚr
SüniÚr

Reputation: 896

Java save temporary data to file

I have this code:

            for (Record record : Adatok) {
            //System.out.println(record.toString2());
            act_data=tmp.testtestclass(record);
            System.out.println("*******");
            System.out.println("Feldolgozás eredménye:");
            System.out.println(data_restructure(act_data));

        //  String content = record.nev + ";" + record.address + "\n"+"asd";

            File file = new File("resultset.csv");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(data_restructure(act_data) + "\n");
            bw.close();


        }

My problem is that this loop running time is hours and can be interupting. So I do this filewrite/bufferedwrite in it. So everytime he get data back than I want to write it to file.

But when I do this it is always write only 1 line to my file than nothing.

How can I improve it? I tried with firewriter, bufferedwriter but It kinda bugging.

I know its a dumb question but I cant figurit out how to solve it cause the basic examples does not works.

Upvotes: 0

Views: 220

Answers (2)

Ben
Ben

Reputation: 3528

You can try to use FileWriter with TRUE parameter:

 FileWriter fw = new FileWriter(file.getAbsoluteFile(),true); //see here!
 BufferedWriter bw = new BufferedWriter(fw);

By doing this, new Text will be appended to the file.

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

Put these lines outside (before) the loop. You are overwriting the file in each loop iteration.

       File file = new File("resultset.csv");
        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

Also,

 bw.close(); // outside (after) the loop

Upvotes: 1

Related Questions