Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 643
user1982519 Avatar asked Oct 14 '13 10:10

user1982519


2 Answers

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!

like image 26
Nick Avatar answered Nov 13 '22 02:11

Nick


You aren't closing the Writer, so you're losing whatever is still in the buffer.

like image 175
user207421 Avatar answered Nov 13 '22 00:11

user207421