Writing output data to text file gives incomplete result in text file

早过忘川 提交于 2019-12-20 01:15:07

问题


I have 14 lists and each list have either numeric or string data. Size of each list is 32561. I have to output a file with the format:

list1_element1   list2_element1.......................list14_element1
list1_element2   list2_element2.......................list14_element2
.
.
.
.
.
list1_element32561   list2_element32561.......................list14_element32561

Each element in output file is separated by tab space. I did it like this in Java.

        out = new BufferedWriter(new FileWriter(fileName));
        for(int i=0; i<32561; i++) {
        out.write(firstList.get(i));
        out.write("\t");
        out.write(secondList.get(i));
        out.write("\t");
        out.write(thirdList.get(i));
        out.write("\t");
        out.write(fourthList.get(i));
        out.write("\t");
        out.write(fifthList.get(i));
        out.write("\t");
        out.write(sixthList.get(i));
        out.write("\t");
        out.write(seventhList.get(i));
        out.write("\t");
        out.write(eighthList.get(i));
        out.write("\t");
        out.write(ninthList.get(i));
        out.write("\t");
        out.write(tenthList.get(i));
        out.write("\t");
        out.write(eleventhList.get(i));
        out.write("\t");
        out.write(twelvethList.get(i));
        out.write("\t");
        out.write(thirteenthList.get(i));
        out.write("\t");
        out.write(fourteenthList.get(i));
            out.write("\t");
        out.write(fifteenthList.get(i));

        out.newLine();
    }
}

My program prints only 32441 lines with the last line consisting of only 6 columns. I don't understand why. Can someone help ?


回答1:


You aren't closing the Writer.




回答2:


The buffer is only written to the stream when its full, or you call the writer.flush() or writer.close() function on it. In your case you just need to add

out.close()

at the end of your program. Otherwise you have data in your buffer which isn't written as the program ends without telling the writer to write the remaining content of its buffer; its holding onto it assuming there will be more data to come!




回答3:


You have not provided complete method code, but issue can be "not closing writer and not flushing output buffers properly".

Use out.flush(); when you need to flush output buffers. And out.close; when you end writing to file.

Or

You can use PrintWriter:

PrintWriter writer = new PrintWriter(new FileWriter("file name"), true);

to get output buffer flushed automatically when println() or format() or printf() called on writer. Or you can manually use writer.flush() to flush output buffer when you desire.



来源:https://stackoverflow.com/questions/19358620/writing-output-data-to-text-file-gives-incomplete-result-in-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!