关于RandomAccessFile的seek和skipBytes

StilesYu 2017-10-29 04:19:54

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 可能问题有点弱智 请见谅
...全文
190 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧