简体   繁体   中英

Why are the last few lines missing from a text file that I'm creating?

I have a function that creates 7 different text files with rows of data. Those 7 files are then combined into a single file in a different function using the following function:

public void createSingle683File(int groupNumber, FileWriter wr){
        try{
            if(new File(printDir+"683_"+groupNumber+".txt").exists()){
                File f683 = new File(printDir+"683_"+groupNumber+".txt");
                BufferedReader input = new BufferedReader(new FileReader(f683));
                String line = null;
                while ((line = input.readLine()) != null){
                    //write contents of existing file to new file
                    wr.write(line+"\n");
                }
                //close bufferedInput
                input.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

The calling code:

    File fileHandle683 = new File(printDir+"683.txt");
                FileWriter wr683 = new FileWriter(fileHandle683);
                for (int groupNumber = 1; groupNumber < 8; groupNumber++){
                    createSingle683File(groupNumber,wr683);
                }
.
.
.
.
.//stuff
wr683.close();

Alaways the final 683.txt is missing about 50 lines from the 7th file (683_7.txt) and I can't figure out why. It's always, and only, the last few lines of the final file that are missing. I can't tell if I am closing the bufferInput to soon or what.

Any ideas would be greatly appreciated. I can test any ideas really quickly.

Thanks!

您要在该FileWriter实例上调用flush()和/或close()吗?

I don't see where you are closing wr683 . I suspect that the data is being left in a buffer when the process shuts down. At least call flush() .

Currently you are not closing the file writer for the final file. So it may be, that the contents you are missing currently are still in the cache of the stream I/O. So close the FileWriter instance of the final file and look at the contents of the file.

So after the for loop you simply enter

wr683.close();

Hope it helps.

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