2

So I wrote a program that is suppose write the contents of two LinkedList into a text file in the format

"header line 1"

"header line 2"

"header line 3"

x1 y1

x2 y2

x3 y3

...

x1023 y1023

Here is the main writing code:

    LinkedList<Double> xVal;
    LinkedList<Double> yVal;
    LinkedList<String> header;
    Analize test;
    Scanner scan = new Scanner(System.in);
    FileWriter fstream;
    BufferedWriter out;

    int i=1;
    test = new Analize(i);
    test.addData();
    test.calculate();


    //Writing ModY
    fstream = new FileWriter("BLOCK " +i+"_ModY.txt");
    out = new BufferedWriter(fstream);
    header = test.getHeader();
    xVal=test.getXList();
    yVal=test.getYListMod();


    //Write Header
    out.write(header.get(0)+"_modY");out.newLine();
    out.write(header.get(1));out.newLine();
    out.write(header.get(2));out.newLine();

    for(int j=0;j<xVal.size();j++)
    {
        double x=xVal.get(j);
        double y=yVal.get(j);
        out.write(x+"\t"+y+" "+j);out.newLine();
        //test code
        System.out.println(xVal.get(j)+"    "+yVal.get(j)+" "+j);
        //System.out.println(j);
    }

The really annoying thing is that the test code line: System.out.println(xVal.get(j)+" "+yVal.get(j)+" "+j); actually ran 1023 time with the correct values in System.in but the file only have values up to the 558th.

I'm not really sure what is happening here...

Lee Chen
  • 23
  • 1
  • 3

2 Answers2

14

I don't see you calling out.close(); anywhere. This will flush and close the underlying stream for you. I would put it right after your for-loop.

Always make sure you close your streams, otherwise some of your data might be hanging out in memory waiting for the JVM to come along and flush it out to your file.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • Thank you so much! I did do that in other sections of the code. I can't believe I didn't see this after around 3 hrs of troubleshooting. – Lee Chen Jul 26 '12 at 01:42
2

In addition to what Cory said, always close the underlying stream in a finally block to make sure that they do get closed regardless of exceptions.

Community
  • 1
  • 1
LanguagesNamedAfterCofee
  • 5,782
  • 7
  • 45
  • 72
  • Doesn't the buffered stream close the underlying stream for you when you close it at the appropriate time? – Neil Jul 25 '12 at 23:33