关于RandomAccessFile的seek和skipBytes
package Day07;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo2 {
public static void main(String[] args) throws IOException {
RandomAccessFile raf
=new RandomAccessFile("raf.txt","rw") ;
String str="I read a book in library";
byte[] data=str.getBytes("UTF-8");
raf.seek(0);
byte [] d=new byte[100];
int len=raf.read(d);
String s=new String(d, 0, len,"UTF-8");
System.out.println(s);
raf.seek(0);
int a=raf.skipBytes(0);
System.out.println(raf.getFilePointer());
raf.seek(0);
System.out.println(raf.getFilePointer());
byte [] d1=new byte[100];
int len1=raf.read(d1);
String s1=new String(d1, 1, len1,"UTF-8");
System.out.println(s1);
raf.close();
}
}
代码如下
输出:I read a book in library,You swimming in sea
0
0
read a book in library,You swimming in sea
看了下skipBytes()的源代码
public int skipBytes(int n) throws IOException {
long pos;
long len;
long newpos;
if (n <= 0) {
return 0;
}
pos = getFilePointer();
len = length();
newpos = pos + n;
if (newpos > len) {
newpos = len;
}
seek(newpos);
/* return the actual number of bytes skipped */
return (int) (newpos - pos);
}Question:skipBytes(0) 输出的是0 指针应该是在0位置 读取时候应该是完整的 I am a Java beginners
但是为什么读取时候变成了 am a Java beginnersx(x为乱码) 指针到了1位置 我通过seek(0) 想把指针
重新调到0位置 却发现原来的1位置变成了0

刚学JAVA 可能问题有点弱智 请见谅

...全文
相关推荐
花1K内存实现高效I/O的RandomAccessFile类
NULL 博文链接:https://x7700.iteye.com/blog/1003918
Java RandomAccessFile 指定位置实现文件读取与写入
主要介绍了Java RandomAccessFile 指定位置实现文件读取与写入的相关资料,需要的朋友可以参考下
java使用RandomAccessFile类基于指针读写文件实例代码
主要介绍了java使用RandomAccessFile类基于指针读写文件实例代码,具有一定参考价值,需要的朋友可以了解下。
android小测面试
1、简述activity的各个生命周期; 3 2、简述ImageView、ImageButton、Button的相同点和不同点; 3 3、死锁是如何造成的; 3 ……
Java随机存取文件.pdf
Java随机存取文件.pdf 学习资料 复习资料 教学资源


Java SE
