[英]Using ReadFully in java
我在Java中使用Readfully来读取文件。 下面的代码对此进行了说明。
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();
}
}
}
Any.txt的内容是Hello World!!
上面的代码打印了Hello World!!
但是当我改变
raf.readFully(arr,0,Length);
至
raf.readFully(arr,3,Length-3);
而不是获得输出lo World!!
,我没有任何错误。
谁能解释一下如何使用。 或者如何获得lo World!!
输出lo World!!
?
默认情况下, readFully
将开始从文件中的当前位置开始读取。 要跳过前三个字符,请使用:
raf.skipBytes(3);
在使用readFully
之前。 另外,没有理由使用偏移量,因此请使用:
raf.readFully(arr,0,Length - 3);
事情会变桃花的。
重要说明:假定前三个字符每个字节只有一个字节,某些字符集不一定是这种情况。 但是,由于这可能是家庭作业或教程的开始,因此这可能是您要寻找的答案。
根据javadoc, readFully(byte[] b, int off, int len)
的off和len参数会影响raf数据在字节数组中的放置位置,而不是读取多少raf数据。 在所有情况下,文件的其余部分均已完全读取。
如果b为null,则抛出NullPointerException。 如果off为负,或者len为负,或者off + len大于数组b的长度,则抛出IndexOutOfBoundsException。 如果len为零,则不读取任何字节。 否则,读取的第一个字节存储在元素b [off]中,下一个字节存储在b [off + 1]中,依此类推。 读取的字节数最多等于len。
试试这个代替:
raf.skipBytes(3);
raf.readFully(arr,3,Length-3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.