[英]Using ReadFully in java
I am using Readfully in java to read a file. 我在Java中使用Readfully来读取文件。 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!!
Any.txt的内容是
Hello World!!
The above code prints Hello World!!
上面的代码打印了
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!!
而不是获得输出
lo World!!
, I get no error. ,我没有任何错误。
Can any one explain me how to use readfully. 谁能解释一下如何使用。 Or how to get the output
lo World!!
或者如何获得
lo World!!
输出lo World!!
? ?
readFully
will start reading from the current position in the file by default. 默认情况下,
readFully
将开始从文件中的当前位置开始读取。 To skip the first three characters, use: 要跳过前三个字符,请使用:
raf.skipBytes(3);
before using readFully
. 在使用
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.
但是,由于这可能是家庭作业或教程的开始,因此这可能是您要寻找的答案。
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. 根据javadoc,
readFully(byte[] b, int off, int len)
的off和len参数会影响raf数据在字节数组中的放置位置,而不是读取多少raf数据。 In all cases the remainder of the file is read fully. 在所有情况下,文件的其余部分均已完全读取。
If b is null, a NullPointerException is thrown.
如果b为null,则抛出NullPointerException。 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.
如果off为负,或者len为负,或者off + len大于数组b的长度,则抛出IndexOutOfBoundsException。 If len is zero, then no bytes are read.
如果len为零,则不读取任何字节。 Otherwise, the first byte read is stored into element b[off], the next one into b[off+1], and so on.
否则,读取的第一个字节存储在元素b [off]中,下一个字节存储在b [off + 1]中,依此类推。 The number of bytes read is, at most, equal to len.
读取的字节数最多等于len。
try this instead: 试试这个代替:
raf.skipBytes(3);
raf.readFully(arr,3,Length-3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.