本文共 2477 字,大约阅读时间需要 8 分钟。
- 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("写入数据成功");
-
- 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 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");
-
-
- }
- }
转载于:https://www.cnblogs.com/kkkore/p/5361308.html