问题描述:文件中显示的还是乱码,编译不报错
代码如下:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class TestPerson {
public static void main(String[] args) {
write();
read();
}
public static void read() {
//创建对象流对象
ObjectInputStream ois=null;
try {
ois = new ObjectInputStream(new FileInputStream("D:\\object11.txt"));
//读取数据
System.out.println(ois.readBoolean());
System.out.println(ois.readInt());
System.out.println(ois.readDouble());
System.out.println(ois.readUTF());
//System.out.println(ois.readChar());
Person p=(Person)ois.readObject();
System.out.println(p);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(ois!=null) {
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void write() {
//创建对象流对象
ObjectOutputStream oos=null;
try {
oos = new ObjectOutputStream(new FileOutputStream("D:\\object11.txt"));
//写入数据
oos.writeBoolean(true);
oos.writeInt(999);
oos.writeDouble(888.88);
oos.writeUTF("朝辞白帝彩云间,千里江陵一日还");
//oos.writeChars("helloworldjava");
oos.writeObject(new Person("临江仙", 20));
//oos.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(oos!=null) {
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
运行结果如下:
