生成和解析txt文件

package txt;

import java.io.BufferedReader;
import java.io.File;
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.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
 * 功能描述:创建TXT文件并进行读、写、修改操作
 * @author lizhiyong
 * @version $Id: ReadWriteFile.java, v 0.1
		2014年8月5日 下午1:27:38 Exp $
 */
public class ReadWriteFile {
    //指定文件路径和名称
    private static String path     = "C:/测试.txt";
    private static File   filename = new File(path);
    private static String readStr  = "    ";

    /**
     * 创建文本文件.
     * @throws IOException 
     * 
     */
    public static void creatTxtFile() throws IOException {
        if (!filename.exists()) {
            filename.createNewFile();
            System.err.println(filename + "已创建!");
        } else {
            filename.delete();
            creatTxtFile();
        }
    }

    /**
     * 读取文本文件.
     * @throws UnsupportedEncodingException 
     * 
     */
    @SuppressWarnings("resource")
    public static String readTxtFile() throws UnsupportedEncodingException {
        String readData = null;
        //BufferedReader br = null;
        BufferedReader br = null;
        try {
            //br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
            br = new BufferedReader(new FileReader(filename));
            try {
                while ((readData = br.readLine()) != null) {
                    System.out.println("readData:" + readData);
                    readStr = readStr + readData + "\r\n";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println("文件内容2是:" + "\r\n" + readStr);
        return readStr;
    }

    /**
     * 给文件写内容.
     * @param content  写入的文件内容
     * @throws IOException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void writeTxtFile(List contentList, HashMap<String, String> map)
                                                                                  throws IOException {
        //先读取原有文件内容,然后进行写入操作
        FileWriter writer = null;
        String filein = map.get("1") + readStr + map.get("2") + readStr + map.get("3") + readStr
                        + map.get("4");
        try {
            writer = new FileWriter(filename, true);
            writer.write(filein);
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }

        for (Iterator iterator = contentList.iterator(); iterator.hasNext();) {
            HashMap<String, String> map2 = (HashMap<String, String>) iterator.next();
            String name = map2.get("name");
            String age = map2.get("age");
            String postion = map2.get("postion");
            String complit = map2.get("complit");
            String filein1 = "\r\n" + name + readStr + age + readStr + postion + readStr + complit
                             + "\r\n";
            try {
                writer = new FileWriter(filename, true);
                writer.write(filein1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }
                }
            }

        }

        readTxtFile();
    }

    /**
     * 将文件中指定内容的第一行替换为其它内容.
     * 
     * @param oldStr
     *            查找内容
     * @param replaceStr
     *            替换内容
     */
    @SuppressWarnings("unused")
    public static void replaceTxtByStr(String oldStr, String replaceStr) {
        String temp = "";
        try {
            File file = new File(path);
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();

            // 保存该行前面的内容
            for (int j = 1; (temp = br.readLine()) != null && !temp.equals(oldStr); j++) {
                buf = buf.append(temp);
                buf = buf.append(System.getProperty("line.separator"));
            }

            // 将内容插入
            buf = buf.append(replaceStr);

            // 保存该行后面的内容
            while ((temp = br.readLine()) != null) {
                buf = buf.append(System.getProperty("line.separator"));
                buf = buf.append(temp);
            }

            br.close();
            FileOutputStream fos = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * main方法测试
     * @param s
     * @throws IOException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] s) throws IOException {
        ReadWriteFile.creatTxtFile();
        //ReadWriteFile.readTxtFile();
        List list = new ArrayList();
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("1", "姓名");
        map.put("2", "年龄");
        map.put("3", "职位");
        map.put("4", "工作单位");

        HashMap<String, String> map2 = new HashMap<String, String>();
        map2.put("name", "李四");
        map2.put("age", "25");
        map2.put("postion", "Java开发工程师");
        map2.put("complit", "上海汽车财务集团有限公司");
        list.add(map2);

        HashMap<String, String> map3 = new HashMap<String, String>();
        map3.put("name", "李四1");
        map3.put("age", "251");
        map3.put("postion", "Java开发工程师1");
        map3.put("complit", "上海汽车财务集团有限公司1");
        list.add(map3);

        ReadWriteFile.writeTxtFile(list, map);
        //        ReadWriteFile.replaceTxtByStr("ken", "zhang");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不讲理的胖子

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

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

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

打赏作者

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

抵扣说明:

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

余额充值