要求1
保存对象信息到文件,并将文件中的对象信息显示出来。
代码
此处对象为一个学生对象
import java.io.*;
class Student implements Serializable{
String number, name;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Example3 {
public static void writeObjectToFile(Object obj, File file) {
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
objectOutputStream.writeObject(obj);
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object readObjectFromFile(File file) {
try {
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
Object o = inputStream.readObject();
inputStream.close();
return o;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args){
Student stu = new Student();
stu.setNumber("123456789");
stu.setName("张三");
File file = new File("test.txt");
writeObjectToFile(stu, file);
Student stu1;
stu1 = (Student) readObjectFromFile(file);
System.out.println("学号:" + stu1.getNumber());
System.out.println("姓名:" + stu1.getName());
}
}
要求2
将保存在本地机当前文件夹中的Ex3_2.HTML文本文件的内容在屏幕上显示出来,然后将其另存为Ex3_2.txt文件。
代码
import java.io.*;
public class Example2 {
public static void main(String[] args) throws IOException {
FileReader in = new FileReader("Ex3_2.HTML");
FileWriter out = new FileWriter("Ex3_2.txt");
BufferedReader br = new BufferedReader(in);
BufferedWriter bw = new BufferedWriter(out);
String str = null;
while((str = br.readLine()) != null){
System.out.println(str);
bw.write(str);
bw.newLine();
}
bw.flush();
in.close();
out.close();
br.close();
bw.close();
}
}