简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM