gpt4 book ai didi

java - 从 java 中的 .txt 读取对象

转载 作者:行者123 更新时间:2023-12-01 23:53:22 25 4
gpt4 key购买 nike

我正在尝试写入并对象到一个文件,然后从文件中读取该对象并对其执行一些操作。该对象可以很好地写入文件,但是当我尝试从文件中检索它时,我什么也没得到。我使用的代码如下:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;


public class Driver
{
public static void main(String[] args) throws IOException, ClassNotFoundException
{
FileOutputStream fos = new FileOutputStream("C:\\Users\\Russian\\Desktop\\file.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);

Person person = new Person("B1234","Roshane","Nolan","male","Spanish Town",new Date(),
"B2134","B3214",150.0,5.11);

oos.writeObject(person);

oos.flush();
oos.close();

//READING FROM THE FILE

FileInputStream fis = new FileInputStream("C:\\Users\\Russian\\Desktop\\file.txt");
ObjectInputStream ois = new ObjectInputStream(fis);


Person object = (Person) ois.readObject();
System.out.println(object);

ois.close();
}

}

最佳答案

我认为您必须通过实现 java.io.Serializable 来序列化 Person 对象来自 API 文档,ObjectInputStream

  ObjectInputStream is used to recover those objects previously serialized. 

代码如下(主要功能与您的相同:

  public static void main(String[] args) throws IOException, ClassNotFoundException 
{
FileOutputStream fos = new FileOutputStream("src/main/resources/Test.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);

Person person = new Person("B1234","Roshane","Nolan","male","Spanish Town",new Date(),
"B2134","B3214",150.0,5.11);

oos.writeObject(person);

oos.flush();
oos.close();

//READING FROM THE FILE

FileInputStream fis = new FileInputStream("src/main/resources/Test.txt");
ObjectInputStream ois = new ObjectInputStream(fis);


Person object = (Person) ois.readObject();
System.out.println(object.toString());


}

人员类别

  import java.util.Date;

public class Person implements java.io.Serializable{

String arg1,arg2,arg3,arg4,arg5,arg6,arg7;
Double d1,d2;
Date date1;
public Person(String string, String string2, String string3,
String string4, String string5, Date date, String string6,
String string7, double d, double e) {
this.arg1=string;
this.arg2=string2;
this.arg3=string3;
this.arg4=string4;
this.arg5=string5;
this.arg6=string6;
this.arg7=string7;
this.d1=d;
this.d2=e;
this.date1=date;


// TODO Auto-generated constructor stub
}

@Override
public String toString()
{
return "Person:"+this.arg1+":"+this.arg2+":"+this.arg3+":"+this.arg4+":"+this.arg5+":"+this.arg6+":"+this.arg7+":"+this.d1+":"+this.d2+":"+this.date1;
}


}

输出:

Person:B1234:Roshane:Nolan:male:Spanish Town:B2134:B3214:150.0:5.11:Sun Apr 14 23:11:27 CDT 2013

关于java - 从 java 中的 .txt 读取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16005318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com