.Txt 文件读写

数据保存在txt 文件中比较简单,也很实用,数据复杂,牵涉的表比较多,选择保存在
txt中比较方便查询。java版网页游戏《倾城》中大量的游戏数据都存放在txt中,我简单的
看了一下,里面设置的任务、玩家行走日志、打怪爆物品 都是存放在txt中,不知道以这种
方式读取是否方便,但速度确实是很快的,下面是我在项目中写的比较简单的txt读写,由于
数据比较琐碎,所以选择保存到txt中,以利于数据统计。

/**
 * @author zjq Mar 27 2010 记录战斗中 所有记录,生成txt 文件
 */
public class TxtUtil {
    /**
     * 创建保存战斗细节的txt文件
     *
     * @param filePath
     * @throws IOException
     */
    public static void createFile(String filePath) throws IOException {
        String fileName = filePath + "//battleRecord.txt";
        File newFile = new File(fileName);
        if (!newFile.exists()) {
            newFile.createNewFile();
        }
    }

    /**
     * 保存每支进入战斗的部队信息以及产生的战斗信息
     *
     * @param fileName
     * @param txtList
     * @throws IOException
     */
    public static void write(String fileName, List<TxtVO> txtList)
            throws IOException {
        File f = new File(fileName + "//battleRecord.txt");
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(f, true);
            bw = new BufferedWriter(fw);
            for (int i = 0; i < txtList.size(); i++) {
                TxtVO tvo = txtList.get(i);
                String str = tvo.getUid() + "," + tvo.getAttOrDef() + ","
                        + tvo.getArmyId() + "," + tvo.getFarmName() + ","
                        + tvo.getArmyName() + "," + tvo.getSName() + ","
                        + tvo.getSt_ct() + "," + tvo.getEd_ct() + ","
                        + tvo.getExp();
                bw.write(str);
                bw.newLine();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bw.flush(); // 将数据更新至文件
            bw.close();
            fw.close();

        }
    }

    /**
     *
     * @param fileName
     * @param endType
     *            结束方式:1:没有回合,战斗结束 2:正常结束
     * @param endString
     *            结果信息,回合数,结束时间
     * @param res
     *            掠夺的资源信息
     * @throws IOException
     */
    public static void writeEndInfo(String fileName, String endType,
            String endString, List<String> res) throws IOException {
        File f = new File(fileName + "//battleRecord.txt");
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(f, true);
            bw = new BufferedWriter(fw);
            bw.write("");
            bw.newLine();
            bw.write("battle result:");
            bw.newLine();
            bw.write(endString);
            bw.newLine();
            if (endType.equals("2")) {
                if (res.size() > 0) {

                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bw.flush(); // 将数据更新至文件
            bw.close();
            fw.close();

        }

    }

    /**
     *
     * @param fileName
     * @param readType
     *            1:读取 战斗部队 2:读取 战斗结果
     * @return
     * @throws IOException
     */
    public static List<String> read(String fileName, int readType)
            throws IOException {
        List<String> txtList = new ArrayList<String>();
        File f = new File(fileName);
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(f);
            br = new BufferedReader(fr);
            if (readType == 2) {
                while (true) {
                    String str = br.readLine();
                    if (str != null && str.equals("battle result:")) {
                        break;
                    }
                }

                while (true) {
                    String str = br.readLine();
                    if (str != null && !str.equals("")) {
                        txtList.add(str);
                    } else {
                        break;
                    }
                }

            } else {
                while (true) {
                    String str = br.readLine();
                    if (str != null && !str.equals("")) {
                        txtList.add(str);
                    } else {
                        break;
                    }
                }
            }
            /*
             * String [] rec = str.split(","); TxtVO tvo = new TxtVO();
             * tvo.setUid(rec[0]); tvo.setAttOrDef(rec[1]);
             * tvo.setArmyId(rec[2]); tvo.setFarmName(rec[3]);
             * tvo.setSName(rec[4]); tvo.setSt_ct(rec[5]); tvo.setEd_ct(rec[6]);
             * tvo.setExp(rec[7]); txtList.add(tvo);
             */

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            br.close();
            fr.close();

        }
        return txtList;
    }

    /**
     * 读取战斗文件,统计攻守双方数据
     *
     * @param request
     * @throws IOException
     */

    public static Map<String, Object> getBattleReport(HttpServletRequest request)
            throws IOException {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        String report_id = request.getParameter("battle_id");// 与战斗id相同
        String fileName = Path.WEB_INF_PATH + "battleInfo/" + report_id
                + "/battleRecord.txt";
        List<String> list = read(fileName, 1);
        List<String[]> att = new ArrayList<String[]>();
        List<String[]> def = new ArrayList<String[]>();

        // 计算所有 单个 部队的 死亡总数 与 经验总数
        Map<String, String[]> map = new HashMap<String, String[]>();
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            String[] s = str.split(",");
            String army = s[1] + "_" + s[2];
            if (map.get(army) == null || map.get(army).equals("")) {// 该部队第一次出现
                int lost = Integer.parseInt(s[6]) - Integer.parseInt(s[7]);
                String[] value = { s[6], lost + "", s[8], s[3], s[4], s[5] };
                map.put(army, value);
            } else {
                // 将死亡兵数 和经验加入
                int lost = Integer.parseInt(s[6]) - Integer.parseInt(s[7]);
                String[] value = map.get(army);
                value[1] = Integer.parseInt(value[1]) + lost + "";
                value[2] = Integer.parseInt(value[2]) + lost + "";
                map.put(army, value);
            }
        }

        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            String[] type = key.split("_");
            if (type[0].equals("1")) {// 攻击方
                att.add(map.get(key));
            } else {
                def.add(map.get(key));
            }

        }
        returnMap.put("att", att);
        returnMap.put("def", def);
        // 统计双方 总计 得失 士兵数+损失+经验
        String att_total = "", def_total = "";
        int[] at = { 0, 0, 0 };
        for (int i = 0; i < att.size(); i++) {
            String[] a = att.get(i);
            at[0] += Integer.parseInt(a[0]);
            at[1] += Integer.parseInt(a[1]);
            at[2] += Integer.parseInt(a[2]);
        }
        att_total = at[0] + "," + at[1] + "," + at[2];

        int[] df = { 0, 0, 0 };
        for (int i = 0; i < def.size(); i++) {
            String[] d = def.get(i);
            df[0] += Integer.parseInt(d[0]);
            df[1] += Integer.parseInt(d[1]);
            df[2] += Integer.parseInt(d[2]);
        }
        def_total = df[0] + "," + df[1] + "," + df[2];

        returnMap.put("att_total", att_total);
        returnMap.put("def_total", def_total);

        List<String> resultList = read(fileName, 2);
        returnMap.put("resultList", resultList);

        return returnMap;

    }

    /**
     * 读取参加战斗的所有玩家 uid
     *
     * @param battle_id
     * @return
     */
    public static Map<String, String> getBattleUid(String battle_id)
            throws IOException {

        String fileName = Path.WEB_INF_PATH + "battleInfo/" + battle_id
                + "/battleRecord.txt";
        List<String> list = read(fileName, 1);
        Map<String, String> map = new HashMap<String, String>();

        Set<String> att = new HashSet<String>();
        Set<String> def = new HashSet<String>();

        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            String[] s = str.split(",");
            if (s[1].equals("1")) {
                att.add(s[0]);
            } else {
                def.add(s[0]);
            }
        }
        String attUid = "", defUid = "";
        for (String str : att) {
            attUid += str + "|";
        }
        attUid = attUid.substring(0, attUid.lastIndexOf("|"));
        map.put("att", attUid);
        for (String str : def) {
            defUid += str + "|";
        }
        defUid = defUid.substring(0, defUid.lastIndexOf("|"));
        map.put("def", defUid);
        return map;
    }

    public static int getBattleRound(HttpServletRequest request)
            throws IOException {
        String report_id = request.getParameter("battle_id");// 与战斗id相同
        String fileName = Path.WEB_INF_PATH + "battleInfo/" + report_id
                + "/battleRecord.txt";
        List<String> resultList = read(fileName, 2);
        String str = resultList.get(0);
        String[] s = str.split(",");
        return Integer.parseInt(s[1]);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值