谁帮我一下啊,怎么会出现空指针异常啊??
import java.io.*;
class TestAccessFile
{
public static void main (String[] args)throws Exception
{
String strinfo=null;
employ e1=new employ("zhangshan",23);
RandomAccessFile v=new RandomAccessFile("1.txt","rw");
v.writeChars(e1.name);
v.close();
RandomAccessFile m=new RandomAccessFile("1.txt","r");
m.seek(0);
for(int i=0;i<employ.LEN;i++)
{
strinfo+=m.readChar();
}
System.out.print(strinfo);
}
}
class employ
{
String name=null;
int age=0;
public static final int LEN=8;
public employ(String name,int age)
{
if(name.length()<employ.LEN)
{
name+="\u0000";
}
else if(name.length()>employ.LEN)
{
name=name.substring(0,employ.LEN);
}
else
{
this.name=name;
this.age=age;
}
}
}
import java.io.*;
class TestAccessFile
{
public static void main (String[] args)throws Exception
{
String strinfo=null;
employ e1=new employ("zhangshan",23);
RandomAccessFile v=new RandomAccessFile("1.txt","rw");
v.writeChars(e1.name);
v.close();
RandomAccessFile m=new RandomAccessFile("1.txt","r");
m.seek(0);
for(int i=0;i<employ.LEN;i++)
{
strinfo+=m.readChar();
}
System.out.print(strinfo);
}
}
class employ
{
String name=null;
int age=0;
public static final int LEN=8;
public employ(String name,int age)
{
if(name.length()<employ.LEN)
{
name+="\u0000";
}
else if(name.length()>employ.LEN)
{
name=name.substring(0,employ.LEN);
}
else
{
this.name=name;
this.age=age;
}
}
}
at java.io.RandomAccessFile.writeChars(RandomAccessFile.java:1035)
at TestAccessFile.main(test1.java:9)
{
name+="\u0000";
}
else if(name.length()>employ.LEN)
{
name=name.substring(0,employ.LEN);
}
这个里面有问题,应该是this.name="\u0000";和this.name=name.substring(0,employ.LEN);吧。属性name没赋值肯定报空指针啦!!!
应该改为
class employ
{
String name=null;
int age=0;
public static final int LEN=8;
public employ(String name,int age)
{
if(name.length() <employ.LEN)
{
name+="\u0000";
}
else
{
name=name.substring(0,employ.LEN);
} this.name=name;
this.age=age;
}
}