黑马程序员技术交流社区

标题: 读取文本,去除以[开头,以]结尾的字符串,并写进文本文件 [打印本页]

作者: fai1017    时间: 2017-12-7 11:43
标题: 读取文本,去除以[开头,以]结尾的字符串,并写进文本文件
操作前效果图:C:\Users\HAI\Desktop\2.png
操作后的效果图:[/img]
源码:
/**
*@time 2017年12月7日 上午10:04:23
*@author ZengFanHai
**/
public class Test {
        public static void main(String[] args) throws IOException {
               
                List<String> list = new ArrayList<>();
                String src = "word.txt";
                String des = "newWord.txt";
                readTxt(list,src);
               
                writeTxt(list,des);
               
        }

        /**
        * @Description: TODO(遍历集合写到文本文件)  
        * @param @param list
        * @param @throws IOException
        * @return void
        */
        public static void writeTxt(List<String> list,String des) throws IOException {
                //创建BufferedWriter对象
                BufferedWriter bw = new BufferedWriter(new FileWriter(des));
                //遍历集合,拿到数据,写入文本文件
                for (String s : list) {
                        bw.write(s);
                        bw.newLine();
                        //bw.flush();
                }
               
                bw.close();
        }

        /**
        * @Description: TODO(读取文本到集合)  
        * @param @throws FileNotFoundException
        * @param @throws IOException
        * @return void
        */
        public static void readTxt(List list, String src) throws IOException {
                BufferedReader br = new BufferedReader(new FileReader(src));
                //一次读一行字符串
                String line = null;
                while((line = br.readLine()) != null) {
//                        String s = line;
//                        String str = s.replaceAll("\\[.*?\\]", "");
                        String s = line;
                        String str = s.replaceAll("\\[.*?\\]", "");
                        list.add(str);
                }
                br.close();
        }

作者: fai1017    时间: 2017-12-7 12:16
操作前文本文件内容:2.png

操作完文本文件内容:3.png

2.png (449.24 KB, 下载次数: 0)

售价: 1 黑马币  [记录]  [购买]

3.png (296.25 KB, 下载次数: 0)

售价: 1 黑马币  [记录]  [购买]






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2