package mytest;
import java.io.RandomAccessFile;
public class RandomFileDemo {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Employee e1 = new Employee("DeanHiroshi", 23);
Employee e2 = new Employee("TaoLei", 320);
Employee e3 = new Employee("SteveJobs", 46);
RandomAccessFile ra = new RandomAccessFile("D:\\OSX\\403\\a.txt", "rw");
ra.write(e1.name.getBytes());
ra.writeInt(e1.age);
ra.write(e2.name.getBytes());
ra.writeInt(e2.age);
ra.write(e3.name.getBytes());
ra.writeInt(e3.age);
ra.close();// ------------------->EASY TO FORGET!!!!!!!!!!!!!!!!
int len = 8;
ra.skipBytes(12);
System.out.println("------------Info of Employee NO.2------------");
String str = "";
for (int i = 0; i < len; i++) {
str += ra.readByte();
}
System.out.println("Name: " + str);
System.out.println("Age: " + ra.readInt());
ra.seek(0);
System.out.println("------------Info of Employee NO.1------------");
str = "";
for (int i = 0; i < len; i++) {
str += ra.readByte();
}
System.out.println("Name: " + str);
System.out.println("Age: " + ra.readInt());
ra.skipBytes(12);
System.out.println("------------Info of Employee NO.3------------");
str = "";
for (int i = 0; i < len; i++) {
str += ra.readByte();
}
System.out.println("Name: " + str);
System.out.println("Age: " + ra.readInt());
ra.close();
}
}
class Employee {
String name;
int age;
static final int SIZE = 8;
public Employee(String name, int age) {
if (name.length() > SIZE)
{
name = name.substring(0, SIZE);
}
else
{
while (name.length() < SIZE)
name += "\u0000";
}
name = this.name;
age = this.age;
}
}
编译出错,提示信息:
Exception in thread "main" java.lang.NullPointerException
at mytest.RandomFileDemo.main(RandomFileDemo.java:16)
各位麻烦帮忙看看,为什么会出现这样的空指针错误呀?如何修改呢?谢谢!
------解决思路----------------------
this.name = name;this.age = age;
------解决思路----------------------
楼上正解~~~
------解决思路----------------------
楼上的楼上确实正解~~~
------解决思路----------------------
楼上正解~~
------解决思路----------------------
楼上正解~~~
------解决思路----------------------
楼上正解~~~