Reputation: 91
I am using Readfully in java to read a file. The below code illustrates it.
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) {
try {
// create a string and a byte array
// create a new RandomAccessFile with filename test
RandomAccessFile raf = new RandomAccessFile("/home/mayank/Desktop/Image/Any.txt", "rw");
// set the file pointer at 0 position
raf.seek(0);
int Length = (int)raf.length();
// create an array equal to the length of raf
byte[] arr = new byte[Length];
// read the file
raf.readFully(arr,0,Length);
// create a new string based on arr
String s2 = new String(arr);
// print it
System.out.println("" + s2);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The contents of Any.txt is Hello World!!
The above code prints Hello World!!
but when I change
raf.readFully(arr,0,Length);
to
raf.readFully(arr,3,Length-3);
Instead of getting the output lo World!!
, I get no error.
Can any one explain me how to use readfully.
Or how to get the output lo World!!
?
Upvotes: 0
Views: 1795
Reputation: 5103
Per the javadoc, the off and len parameters of readFully(byte[] b, int off, int len)
affect where in your byte array the raf data is placed, not how much of the raf data is read. In all cases the remainder of the file is read fully.
If b is null, a NullPointerException is thrown. If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown. If len is zero, then no bytes are read. Otherwise, the first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes read is, at most, equal to len.
try this instead:
raf.skipBytes(3);
raf.readFully(arr,3,Length-3);
Upvotes: 1
Reputation: 5438
readFully
will start reading from the current position in the file by default. To skip the first three characters, use:
raf.skipBytes(3);
before using readFully
. Also there's no reason to use an offset, so use:
raf.readFully(arr,0,Length - 3);
and things will be peachy.
IMPORTANT NOTE: This assumes that the first 3 characters are only one byte a piece, which isn't necessarily the case with some character sets. But since this is likely a beginning homework assignment or tutorial, this is likely the answer you're looking for.
Upvotes: 1