简体   繁体   English

Java将临时数据保存到文件

[英]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. 但是,当我这样做时,总是只向我的文件写入1行,什么也没有。

How can I improve it? 我该如何改善? I tried with firewriter, bufferedwriter but It kinda bugging. 我尝试使用firewriter,bufferedwriter,但这有点麻烦。

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: 您可以尝试使用带有TRUE参数的FileWriter:

 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. 这样,新的文本将被附加到文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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