我正在尝试将矢量写入和读取文本文件。我创建了一个类 WriteVectorToFile(如下所示),它创建了一个包含名为 Car 的类的对象的向量。Car 类实现了 Serializable 并且仅包含带有 setter 和 getter 方法的信息。在 WriteVectorToFile 类中,我创建了一个 createVector() 方法和 writetoFile() 方法,它们可以工作。readtoFile() 方法中的问题,它给出了一个错误(如下所列)。我想知道我做错了什么以及导致问题的原因。
The error :
java.lang.NullPointerException
at WriteVectorToFile.readtoFile(WriteVectorToFile.java:73)
at WriteVectorToFile.main(WriteVectorToFile.java:110)
at __SHELL1.run(__SHELL1.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at bluej.runtime.ExecServer$3.run(ExecServer.java:725)
代码:
import java.io.*;
import java.util.Vector;
public class WriteVectorToFile{
private Car car1;
private Vector garage;
private File myFile;
private FileOutputStream out;
private FileInputStream in;
private ObjectInputStream objin;
private ObjectOutputStream objout;
public WriteVectorToFile(){
this.myFile = new File("E:/JAVA/My Java Programs/MyVectorFile.txt");
try{
myFile.createNewFile();
System.out.println("New File --> Success.");
}catch(IOException e){
e.printStackTrace();
System.out.println("New File --> Fail.");
}
}
private void writetoFile(){
try{
out = new FileOutputStream(myFile);
objout = new ObjectOutputStream(out);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try{
objout.writeObject(garage);
objout.close();
System.out.println("Write File --> Success.");
}catch(IOException e){
System.out.println("Write File --> Fail.");
e.printStackTrace();
}
}
private void readtoFile(){
try{
FileInputStream in = new FileInputStream(myFile);
ObjectInputStream objin = new ObjectInputStream(in);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
// Object obj = null;
Vector tempVec = new Vector();
try{
ERROR Line 73 : tempVec = (Vector) objin.readObject();
objin.close();
System.out.println("Read File --> Success.");
}catch(Exception e){
System.out.println("Read File --> Fail.");
e.printStackTrace();
}
//Car tempg = new Car();
//tempg = (Car) vecNew.firstElement();
//System.out.println(tempg.toString());
//System.out.println(((Car)(vecNew.firstElement())).toString());
}
private void createVector(){
this.garage = new Vector();
// To create a vector with a specific datatype add <type>
// Vector garage = new Vector<Car>();
car1 = new Car("3245","Toyota","Ferry23",(double)34500);
this.garage.add(car1);
this.garage.add(new Car("3232","Fiat","MozoZ3",(double)25000));
this.garage.add(new Car("2345","Mazda","ZenFix",(double)13700));
}
public static void main (String[] args){
WriteVectorToFile test = new WriteVectorToFile();
test.createVector();
test.writetoFile();
test.readtoFile();
}
}