[英]Correctly serializing objects in java
誰能幫助我發現錯誤? 我試圖通過序列化將某些信息(最小/最大/平均年齡)從文件people.txt(由200行組成,例如'Christel; MacKay; 4“ 2”; 38')傳遞到另一個文件。第一堂課,在這里我處理有關這些人的一些信息:
import java.io.Serializable;
@SuppressWarnings("serial")
public class Person implements Serializable
{
private String firstname;
private String lastname;
private int age;
public Person (String PersonFN, String PersonLN, int PersonA)
{
firstname = PersonFN;
lastname = PersonLN;
age = PersonA;
}
public String toString()
{
return "Name: "+firstname+" "+lastname+" Age: "+age;
}
public int getAge()
{
return age;
}
}
另一個完成所有工作:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;
public class Collection
{
int min;
int max;
int total;
private static ArrayList<Person> people;
public Collection()
{
people = new ArrayList<Person>();
min = 100;
max = 1;
total = 0;
}
BufferedReader fr = null;
BufferedWriter fw = null;
public void readFromFile() throws IOException
{
fr = new BufferedReader (new FileReader("people.txt"));
String line = null;
StringTokenizer st;
while (fr.ready())
{
line = fr.readLine();
st = new StringTokenizer(line);
String name = st.nextToken(";");
String surname = st.nextToken(";").toUpperCase();
String height = st.nextToken(";");
int age = Integer.parseInt(st.nextToken(";").trim());
Person p = new Person (name, surname, age);
p.toString();
people.add(p);
//for the 2nd part
if(age < min)
min = age;
if (age > max)
max = age;
total = total + age;
}
}
public int minAge()
{
int minA = 100;
for (int i = 0; i < people.size(); i++)
{
Person p = people.get(i);
int age = p.getAge();
if (age < minA)
{
minA = age;
}
}
System.out.print(minA+"; ");
return minA;
}
public int maxAge()
{
int maxA = 1;
for (int i = 0; i < people.size(); i++)
{
Person p = people.get(i);
int age = p.getAge();
if (age > maxA)
{
maxA = age;
}
}
System.out.print(maxA+"; ");
return maxA;
}
public float avgAge()
{
int sum = 0;
for (int i = 0; i < people.size(); i++)
{
Person p = people.get(i);
int age = p.getAge();
sum = sum + age;
}
float avgA = sum / people.size();
System.out.print(avgA);
return avgA;
}
public int fastMinAge()
{
//System.out.print("Minimum age: " + min);
return min;
}
public int fastMaxAge()
{
return max;
}
public float fastAvgAge()
{
return total / people.size();
}
public void writeToFile(String filename) throws IOException
{
StringBuffer val = new StringBuffer ("Minimum age: ");
val.append(fastMinAge());
val.append("\n Maximum age: ");
val.append(fastMaxAge());
val.append("\n Average age: ");
val.append(fastAvgAge());
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
String outText = val.toString();
out.write(outText);
out.close();
}
public static void main(String[] args) throws IOException, ClassNotFoundException
{
Collection c = new Collection();
c.readFromFile();
for(Person d: people)
{
System.out.println(d);
}
c.minAge();
c.maxAge();
c.avgAge();
c.fastMinAge();
c.fastMaxAge();
c.fastAvgAge();
c.writeToFile("RESULTS.txt");
String filename = "people.txt";
//FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename));
os.writeObject(c);
os.close();
String filename1 = "results1.txt";
FileInputStream fis = new FileInputStream(filename1);
ObjectInputStream ois = new ObjectInputStream(fis);
Collection p = (Collection) ois.readObject();
ois.close();
}
}
當我運行代碼時,它將創建RESULTS.txt文件並在其中添加正確的信息。 我確定這部分確切的代碼出了點問題:
String filename = "people.txt";
//FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename));
os.writeObject(c);
os.close();
String filename1 = "results1.txt";
FileInputStream fis = new FileInputStream(filename1);
ObjectInputStream ois = new ObjectInputStream(fis);
Collection p = (Collection) ois.readObject();
ois.close();
順便說一下,我的people.txt文件更改為“¬ķ{sr java.io.NotSerializableException(Vxē5xrjava.io.ObjectStreamExceptiondĆäk¨9ūßxr?java.io.IOExceptionl€sde%š«xr?java。 lang.ExceptionŠż>;Äxr?java.lang.ThrowableÕĘ5'9wøĖL Causet Ljava / lang / Throwable; L detailMessaget Ljava / lang / String; [stackTracet [Ljava / lang / StackTraceElement; L rejectedExceptionst?Ljava / util / List; xpq 〜t SD3lab1.Collectionur [Ljava.lang.StackTraceElement; F * <<ż“ 9 xp sr java.lang.StackTraceElementaÅ&6Ż…I lineNumberL?declaringClassq〜L fileNameq〜L methodNameq〜xp˙˙˙˙tjava.io.ObjectOutputStreampt writeObject0sq〜〜q〜?pt?writeObjectsq〜©q〜t?Collection.javat mainsr&java.util.Collections $UnmodifiableListü?%1µģˇ?L listq〜xr,java.util.Collections $ UnmodifiableCollectionB€Ė^÷L ct Ljava / util / Collection; xpsr?java.util.ArrayListxŅ™ĒaI sizexp w xq〜x“,然后在控制台上收到以下錯誤:
Exception in thread "main" java.io.NotSerializableException: SD3lab1.Collection
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at SD3lab1.Collection.main(Collection.java:169)
非常感謝您的幫助
您需要將Collection
標記為Serializable
public class Collection implements Serializable {
另外, BufferedReader
和BufferedWriter
不可序列化,因此需要標記為transient
private transient BufferedReader fr;
private transient BufferedWriter fw;
另外,使用類名稱(例如Collection
也勢必引起混亂。 考慮重命名該類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.