为什么使用rf.writeUTF()写入字符串时,当字符串为空时,rf.getFilePointer()返回为18,当String越长,文件指针反而指向的更前。小弟是菜鸟,希望大家多多指点!直接附上代码。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String a = File.separator;
String s1 = "C:" + a + "test";
File file = new File(s1);
Student stu1 = new Student("jjkbwqdsa", 20);
Student stu2 = new Student("1fdasdasd7", 20);
Student stu3 = new Student("啵啵啵", 20);
if (!(file.exists())) {
file.mkdir();
}
RandomAccessFile rf = new RandomAccessFile(new File(file, "1.txt"),
"rw");
try {
rf.writeUTF(stu1.name);
System.out.println("此时文件指针当前位置:"+rf.getFilePointer());
//此时文件指针当前位置:10
rf.writeInt(stu1.age);
System.out.println("此时文件指针当前位置:"+rf.getFilePointer());
//此时文件指针当前位置:14
rf.writeChars(stu2.name);
System.out.println("此时文件指针当前位置:"+rf.getFilePointer());
//此时文件指针当前位置:30
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rf.seek(31);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rf.writeUTF(stu3.name);
System.out.println("此时文件指针当前位置:"+rf.getFilePointer());
//此时文件指针当前位置:52 ????这个怎么由30一下跳到52了,求解!
}
}
class Student {
String name;
int age;
private static final int LEN = 8;
public Student(String name, int age) {
if (name.length() > LEN) {
name = name.substring(0, 8);
} else {
while (name.length() < LEN)
name = name + "\u0000";
}
this.age = age;
this.name = name;
}
}