对保存在txt文件中的一个Object类对象的增删改方法实现的总结

1. 假设
	这个Object具有以下属性(可能还有其它属性,这里举例便于理解就不写多了):
	id,name,price;
如果如果这个对象是图书,那么对图书的增删改应该是图书管理员的操作
,所以,可以将增删改定义成为一个接口,对应的方法就应该是:
interface IMgr{
	//得到所有Object对象列表
	Object getObjectList();
	//得到指定的Obj 根据id
	Object get(int id);
	//添加对象o
	boolean addObj(Object o);
	//删除对象o
	boolean delObj(int id);
	//更新对象o
	boolean updateObj(Object o);
}
2. 接口IMgr的实现类
class IMgr_impl implements IMgr{
	//重写所有IMgr的方法,具体实现方法后面详细介绍
	public Object getObjectList(){}
	public Object get(int id){}
	public boolean addObj(Object o){}
	public boolean delObj(int id){}
	public boolean updateObj(Object o){}
}
3. getObjectList()方法的实现:
	@Override
    public List<Object> getObjectList() {
    	//创建一个objectList用来存放从文件读取的Object对象
        List<Object> objectList = new ArrayList<>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(
                    new FileReader(MyUtil.getPath())
            );
            String str = null;
            while ((str = br.readLine()) != null) {
                String fileDataList[] = str.split("\\s+");
                int id = Integer.parseInt(fileDataList[0]);
                String name = fileDataList[1];
                String price = fileDataList[2];
                //new()一个新的Object对象tempObj
                Object tempObj = new(id,name, price);
                //调用List的add方法将每读取一行的tempObj添加到objectList当中
                objectList .add(tempObj );
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //当整个txt文件的文件读取完成之后,表示所有的Object对象的数据已经全部放入到objectList 这个List集合当中了,将objectList返回给这个方法的调用者(也就是数据操作员)。
        return objectList ;
    }
4. get(int id)方法的实现:
	@Override
    public Object get(int id) {
    	//定义一个值为null的对象o
        Object o = null;
        BufferedReader br = null;
        try {
            br = new BufferedReader(
                    new FileReader(MyUtil.getPath())
            );
            String str = null;
            while ((str = br.readLine()) != null) {
            	//定义一个fileDataList字符串数组,保存Object对象数据
                String fileDataList[] = str.split("\\s+");
                int tempId = Integer.parseInt(fileDataList[0]);
                if (i == tempId) {
                    o = new Object();
                    o.setId(tempId);
                    o.setName(fileDataList[1]);
                    o.setPrice(fileDataList[2]);
                }
                return o;//返回对象o
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;//如果没有指定对象,就返回null
    }
5. addObj(Object o)方法的实现:
    @Override
    public boolean addObj(Object o) {
    	//定义一个objectList获取存放所有的Object对象
    	//这里调用了getObjectList()方法来获取文件当中的object对象
        List<Object> objectList = getObjectList();
        //判断传入的对象是否为空
        if (o != null && o.getId() > 0) {
            objectList.add(o);
            //使用printwrither进行文件写入,将已经新增过一个对象o的objectList的数据重新写入txt文件
            PrintWriter out= null;
            try {
                out= new PrintWriter(MyUtil.getPath());
                //使用for-each遍历objectList集合
                for (Object obj : objectList) {
                    String str = obj.getId() + " " +
                            obj.getName() + " " +
                            obj.gethPrice();
                    out.println(str);
                    //刷新缓存
                    out.flush();
                }
                return true;//添加成功 返回true
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();//关闭流
                }
            }
        }
        return false;//添加失败  返回false
    }
6. delObj(int id)方法的实现:
 @Override
    public boolean delHouse(int id) {
        //定义一个objectList获取存放所有的Object对象
    	//这里调用了getObjectList()方法来获取文件当中的object对象
        List<Object> objectList = getObjectList();
        boolean isExisted = false;//标记指定id的object对象是否存在文件当中,为true表示存在,否则为false
        //使用for循环遍历objectList集合
        for (int i = 0; i < objectList.size(); i++) {
        	//定义一个临时的object对象o
            Object o = objectList.get(i);
            if (id == o.getId()) {
                isFind = true;//id 跟集合当中的某个对象o的id相等
                houseList.remove(o);//调用集合.remove()方法移除对象o
                break;//推出方法
            }
        }
        //删除传入id的对象之后需要对文件进行重新写入
        if (isExisted) {
            PrintWriter out = null;
            try {
                out = new PrintWriter(MyUtil.getPath());
                for (Object obj: objectList) {
                    String str = obj.getId() + " " +
                            obj.getName() + " " +
                            obj.getPrice() ;
                    out .println(str);//写入并换行
                    out.flush();//刷新缓存
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out .close();//关闭文件
                }
            }
            return true;
        }

        return false;
    }
7. updateObj(Object o)方法的实现:
@Override
    public boolean updateObj(Object o) {
        List<Object> objectList = getObjectList();
        int index = -1;
        boolean isExisted = false;
        for (int i = 0; i < objectList.size(); i++) {
            if (o.getId() == objectList.get(i).getId()) {
                isExisted = true;
                index = i;
                break;
            }
        }

        if (isExisted) {
            objectList.get(index).setId(o.getId());
			objectList.get(index).setName(o.getName());
            objectList.get(index).setPrice(o.getPrice());
            
            PrintWriter out = null;
            try {
                out = new PrintWriter(MyUtil.getPath());
                for (Object obj : objectList) {
                    String str = obj.getId() + " " +
                            obj.getName() + " " +
                            obj.getPrice();
                    out.println(str);
                    out.flush();
                }
                return true;//更新成功返回true
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out .close();
                }
            }
        }
        return false;//如果对象o不在文件中则更新失败 返回false
    }
8. 关于MyUtil.getPath()方法的实现:
因为所有给增删改操作都涉及到文件的读取,很多地方都需要获取文件路径,所以可以将这个方法写在MyUtil这个工具类当中,需要用的时候,直接调用方法就好了
1. 这个类需要用到的java包:
	import java.io.FileInputStream;
	import java.io.FileNotFoundException;
	import java.io.IOException;
	import java.io.InputStream;
	import java.util.Properties;
2. 文件夹:
	在项目文件下新建文件夹res,将Object.txt放在里面
	然后需要在res文件夹里面创建一个path.properties
	![??](https://img-blog.csdnimg.cn/2020080516290463.png)
	在path.properties里面写:filepath=res/object.txt
3. 实现:
public class MyUtil {
	//定义一个PATH常量标记配置文件path.properties的路径
    private static final String PATH = "res/path.properties";
    //定义FILE_PATH_KEY常量标记配置文件path.properties中的filepath
    private static final String FILE_PATH_KEY = "filepath";
    
    public static String getPath() {
        Properties pps = new Properties();
        InputStream is = null;
        Object o = null;
        try {
            is = new FileInputStream(PATH);
            pps.load(is);
            o = pps.getProperty(FILE_PATH_KEY);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return o.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

国服酱紫牙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值