1

I am writing to a .dat file in Java that will produce results in binary. I am using randmAccessFile to get these results.

I can get my code to work for 1 line, but when I put it into a for loop to create 10 lines of code, I get an Exception.

Here is my code so far:

public static void main (String [] args) throws IOException
{ 
    DateFormat df = new SimpleDateFormat("dd-MM-yy-HH");
    Date date = new Date();
    System.out.println(df.format(date));

    File fileName = new File(df.format(date) + ".dat");
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");

    for(int i = 0; i < 10; i++)
    {   
        raf.writeLong(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis());
        raf.writeInt(10);
        raf.writeInt(2);
        raf.write((byte)1);
        raf.writeInt(3);
        raf.close();    
    }
}

If the for loop was taken out, the code will work but trying to run it as is produces the following results;

04-11-13-15
Exception in thread "main" java.io.IOException: Stream Closed
    at java.io.RandomAccessFile.write0(Native Method)
    at java.io.RandomAccessFile.write(Unknown Source)
    at java.io.RandomAccessFile.writeLong(Unknown Source)
    at com.davranetworks.seleniumtests.Example.main(Example.java:28)

Can anyone explain what I am suddenly doing wrong and be able to send me in the right direction?

4
  • 3
    Why do you have raf.close() inside your for? Commented Nov 4, 2013 at 15:55
  • just seen it and after moving it outside of the loop, it works now Commented Nov 4, 2013 at 15:58
  • 2
    Consider deleting the question. Commented Nov 4, 2013 at 15:58
  • If your question is answered, please mark an answer as accepted. Commented Nov 4, 2013 at 16:20

2 Answers 2

1

Your For Loop will go from 1 to 10.

consider for 1st pass 0

it will execute below lines along with last line which is closing RandomAcessFile raf.

  raf.writeLong(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis());
        raf.writeInt(10);
        raf.writeInt(2);
        raf.write((byte)1);
        raf.writeInt(3);
        raf.close();    

Now for pass 1 it tries to again execute above 6 lines but in first line only it will throw the exception as file is closed and you are trying to operate on that.

Sign up to request clarification or add additional context in comments.

Comments

0

I figured it out, just put the raf.close() outside of the for loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.