wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Need help.-RandomAccessFile again Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Need help.-RandomAccessFile again" Watch "Need help.-RandomAccessFile again" New topic
Author

Need help.-RandomAccessFile again

Chris Ben
Ranch Hand

Joined: Jan 15, 2001
Posts: 135
Hi,
I have never used RAF before and am stuck again. Help needed! Please see the codes below:
import java.io.*;
public class RandomPractice
{
// RandomAccessFile r1=new RandomAccessFile("d:\\temp", "rw");
//Q1:The program will not compile with the line above, no idea
//about how to handle it.
public static void main(String[] afg) throws IOException {
File f=new File("d:\\java2-certificate/access2.doc");
RandomAccessFile r4=new RandomAccessFile(f, "rw");
r4.writeBytes("test-writeByte");
//so far, everything is fine
System.out.println("output of readByte()is "+r4.readByte());
//Q2: No problem in compiling, but I got errors in running time.
//NO idea about what is going on?
//Q3: Can someone tell me how how to use method writebyte(int b)?
}
}
Thanks a lot
Ben
Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
i got the following program to run:
import java.io.*;
public class a1 {
public static void main(String args[]) throws IOException
{RandomAccessFile raf = new RandomAccessFile("test.java", "rw");
raf.writeBytes("Just for test");
String s;
raf.seek(0);
while ((s = raf.readLine()) != null) System.out.println(s);
raf.close();
}
}
some interesting facts:
1.) notice that i had to reset the pointer before i could read what i just wrote.
2.) there is no equivalent to read(byte[]) in the readChar() method. I mean, there is no method like readChar(char[]).
3.) when i was trying to read into bytes(which gave me some garbled up output) i used
long l = raf.length();
but to create an array i had to cast this l to an int type as in
byte[] buf = new byte[(int) l];
Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
regd how to use writeByte()....
well, didn't try it but you can pass any char type in the argument , like -
raf.writeByte('c');
I tried raf.writeByte('c');
and raf.writeByte(65);
in my earlier code b4 reading and this is the output i got -
Just for testcA
So, works fine i guess!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Need help.-RandomAccessFile again
 
Similar Threads
Quession obout I/O
B&S: Server Shutdown
Random Access File modes
questions about several File methods.
I/0 Quession