关于RandomAccessFile的seek和skipBytes

StilesYu StilesYu 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

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 可能问题有点弱智 请见谅
...全文
评论
收藏 已收藏
分享
返回顶部
StilesYu
Java SE 62,620 成员 307,251 内容