【发布时间】:2014-08-25 06:33:05
【问题描述】:
所以,我试图从文件中读取一个对象,但我不知道为什么会出现这个异常,或者如何解决它。也许你们可以帮助我?我试过弄乱我阅读对象的方式,但不能完全正确。这是我的代码,我在读取 listOfEmployeesIn[i] = (Employee) objIn.readObject();:
import java.util.Random;
import java.io.*;
public class ProjectFive{
public static void main(String[] args) throws IOException{
Random rn = new Random();
RandomAccessFile file = new RandomAccessFile("employees.txt", "rw");
FileOutputStream fileOut = new FileOutputStream("employees.txt");
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
FileInputStream fileIn = new FileInputStream("employees.txt");
ObjectInputStream objIn = new ObjectInputStream(fileIn);
Object x;
long SSN;
float salary;
int age;
float maxSalary = 200000;
float minSalary = 20000;
long SSNRange = 1000000000;
String[] names = {"Matty Villa"};
Employee[] listOfEmployeesOut = new Employee[20];
Employee[] listOfEmployeesIn = new Employee[20];
for(int i=0;i<listOfEmployeesOut.length;i++){
SSN = (long)(rn.nextDouble()*SSNRange);
salary = rn.nextFloat()*(maxSalary - minSalary)+minSalary;
age = rn.nextInt(57)+18;
listOfEmployeesOut[i] = new Employee(SSN, names[i], salary, age);
}
for(int i = 0;i<listOfEmployeesOut.length;i++){
objOut.writeObject(listOfEmployeesOut[i]);
}
for(int i = 0;i<listOfEmployeesIn.length;i++){
listOfEmployeesIn[i] = (Employee) objIn.readObject();
}
file.close();
fileOut.close();
objOut.close();
fileIn.close();
objIn.close();
}
}
class Employee implements Serializable{
public long socialSecurityNumber;
public String fullName;
public float salary;
public int age;
public Employee(long socialSecurityNumber, String fullName, float salary, int age){
this.socialSecurityNumber = socialSecurityNumber;
if(fullName.length() != 50){
fullName = resizeString(fullName);
}
this.fullName = fullName;
this.salary = salary;
this.age = age;
}
private String resizeString(String s){
if(s.length() < 50){
for(int i = s.length(); i<=50; i++){
s += ' ';
}
}else{
s = s.substring(0,50);
}
return s;
}
public String toString(){
String out = "Name: " + fullName + "\nSalary: " + salary + "\nSocial: " + socialSecurityNumber
+ "\nAge: " + age;
return out;
}
}
【问题讨论】:
-
总是发布堆栈跟踪。这通常表明您没有可用的库,其中包含您尝试读取的流中的某些对象的类定义。
-
您是否在抱怨编译错误?
标签: java exception objectinputstream classnotfound