• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help regarding File Handling

 
Lalit G
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can anybody pls tell how the foll'n program excecutes n what'll be the Output.
Thanks in advace.
lalit
import java.io.*;
public class TestIO {
public static void main(String args[]) throws IOException {
RandomAccessFile file = new RandomAccessFile("test.txt", "rw");
file.writeBoolean(true);
file.writeInt(123456);
file.writeInt(7890);
file.writeLong(1000000);
file.writeInt(777);
file.writeFloat(.0001f);
file.seek(2);
System.out.println(file.readInt());
file.close();
}
}
 
Detlev Beutner
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have just to compare with the API:

1.) The "true" is written as (byte) 1. So you have
1

2.) The "123456" is written as an integer of four bytes, the system is, let v be the int:
1. (byte) (0xff & (v >> 24))
2. (byte) (0xff & (v >> 16))
3. (byte) (0xff & (v >> 8))
4. (byte) (0xff & v)
So you have with the "true" together:
1 0 1 226 64

3.) The same for the 7890, yo you have:
1 0 1 226 64 0 0 30 210

4.) The following lines of written things don't matter. Have a look at the file.seek: It sets offset to two. So you start reading the third byte. You are reading with file.readInt, which works this way, if b1 .. b4 are the four bytes read:
int = (b1 << 24) | (b2 << 16) + (b3 << 8) + b4
In this example:
int = (1 << 24) | (226 << 16) + (64 << 8) + 0 = 31604736
which is the output.

Hope it helps
Detlev
[This message has been edited by Detlev Beutner (edited July 16, 2001).]
 
Lalit G
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx
Detlev Beutner
Lalit.
 
Lalit G
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx
Detlev Beutner
Lalit.
 
Lalit G
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tell me pls Detlev
if seek(5)is there instead of seek(2).How it'll work.
I'm confused how seek()method works.
pls help me regarding this.
Thanx in advance.
Lalit.
 
Detlev Beutner
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at my answer given above:
"Have a look at the file.seek: It sets offset to two. So you start reading the third byte."
So if you set offset to 5, you start reading the 6th byte (setting offset to n means: leave n elements untouched and than start processing).
Hope it helps
Detlev
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!