- package Login;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- public class ObjectOutTest {
- /* 将对象写入文件方法 */
- public void write(Object o, String path) {
- try {
- /* 创建存取文件 */
- FileOutputStream fileStream = new FileOutputStream(path);
- /* 将存取文件写入对象 */
- ObjectOutputStream os = new ObjectOutputStream(fileStream);
- /* 写入对象 */
- os.writeObject(o);
- System.out.println("写入数据成功");
- /* 关闭ObjectOutputStream */
- os.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /* 将对象从文件中读出来 */
- public void read(String path) {
- try {
- /* 连接到要读取的文件 */
- FileInputStream fileStream = new FileInputStream(path);
- /* 怎样读取连接到的文件 */
- ObjectInputStream os = new ObjectInputStream(fileStream);
- /* 读取对象 */
- Dog dog = (Dog) os.readObject();
- System.out.println("输出结果:" + dog.getName() + " is a "
- + dog.getSex() + ",高:" + dog.getHeight() + ",长:"
- + dog.getLength());
- /* 关闭对象 */
- os.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- /* 往文件写入字符串 */
- public void wirteString(String path, String context) {
- try {
- /* 创建写入对象 */
- FileWriter fileWriter = new FileWriter(path);
- /* 创建缓冲区 */
- BufferedWriter writer = new BufferedWriter(fileWriter);
- /* 写入字符串 */
- writer.write(context);
- /* 关掉对象 */
- writer.close();
- System.out.println("写入字符串成功!");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /* 读取文件中的字符串 */
- public void readString(String path) {
- try {
- /* 创建读取对象 */
- FileReader fileReader = new FileReader(path);
- /* 创建缓存区 */
- BufferedReader reader = new BufferedReader(fileReader);
- /* 读取文件 */
- String line = null;
- while ((line = reader.readLine()) != null) {
- System.out.println("读取成功:" + line);
- }
- /* 关闭对象 */
- reader.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /* 出函数入口 */
- public static void main(String args[]) {
- // Dog为外部类必须序列化才能实现它的对象的读取
- Dog d = new Dog();
- d.setHeight(12);
- d.setLength(23);
- d.setName("bobi");
- d.setSex('b');
- ObjectOutTest qqt = new ObjectOutTest();
- qqt.wirteString("F:/IO/cc.sex", "chengchao 123456789");
- qqt.readString("F:/IO/cc.sex");
- }
- }
IO流的文件写入与读取
最新推荐文章于 2024-04-23 11:56:27 发布