WriteInt-RandomAccessFile - java

Go To StackoverFlow.com

2

i am trying to write a program in java (on linux) using RandomAccessFile class for writing to files.

for some really weird reason it is not working. the most simplest code does not work. when try to use :

RandomAccessFile file = new RandomAccessFile("a.txt", "rw");
file.writeInt(3);
file.close();

it ether leaves the file blank or fills it with gibrish

i assume it has to do with some encoding issue i am not familiar with.

any one have any thoughts about it?

thank you

2012-04-03 19:49
by bachurim09
Well writing a 3 in binary and then trying to view it in a regular text editor will of course print giberish. In ASCII the 3 corresponds to End of text - Hiro2k 2012-04-03 20:04
@Hiro2k this is an answer. post it as suc - Guillaume Polet 2012-04-03 20:06


2

It simply writes a 32-bit integer to the file (in your case it is the bytes sequence 00 00 00 03). If you want to write it as a string, you need to

    RandomAccessFile file = new RandomAccessFile("a.txt", "rw");
    file.writeBytes(Integer.toString(3));
    file.close();
2012-04-03 20:11
by Eugene Retunsky


-2

You would be best served going thru a tutorial like this one to learn how to use random access files

http://www.java-tips.org/java-se-tips/java.io/how-to-use-random-access-file.html

2012-04-03 19:55
by ControlAltDel
i did read tutorials, but almost none of them use writeInt, and also the ones that do and i copy paste them, they also don't work - bachurim09 2012-04-03 20:00