누구든지 실수를 찾아 낼 수 있습니까? serialize하여 people.txt 파일 ('Christel, MacKay, 4'2 ', 38'와 같은 200 줄로 구성된 파일)에서 특정 파일 (최소/최대/평균 연령)을 다른 파일로 전달하려고합니다. 여기 있습니다. 모든 일을자바에서 객체를 올바르게 직렬화하면
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 ē † 5 xr java.io.ObjectStreamExceptiondecäk¨9ūß xr java.io.IOExceptionl € sde % š« Throwable, L detailMessaget Ljava/lang/String; [] StackTracet [Ljava/lang/StackTraceElement] L 억제 된 Ljava/util/목록; XPQ ~ SD3lab1.Collectionur [Ljava.lang.StackTraceElement t, F * < < Z "9 XP SR java.lang.StackTraceElementa Å & 6Z ... I lineNumberL declaringClassq ~ L fileNameq ~ L methodNameq ~ XP t java.io.ObjectOutputStreampt writeObject0sq ~ ˙ ˙˙˙q ~ pt writeObjectsq ~ © q ~ t Collection.javat mainsr & java.util.Collections $ UnmodifiableListü % 1μģ listq ~ xr, java.util.Collections $ UnmodifiableCollectionB € Ė^÷ L ct Ljava/util/컬렉션, xpsr java.util.ArrayListxŅ ™ EA I 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 c = 새 Collection();'??? 왜 콜렉션을 구현하는거야? 그것은 인터페이스이므로 사용할 수있는 구현이 많이 있습니다! – alfasin
@OleksiyMartynov, c는 "Collection c = new Collection();"입니다. 이전에 사용 했었지만 필자는 직렬화하는 방법을 확실히 모릅니다. 올바른 수업을 듣고 있습니까? – user2962334