Reputation: 2098
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?
Upvotes: 1
Views: 334
Reputation: 6111
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.
Upvotes: 1