读取文件生成新文件

    public void makeTxt(){
        String tempString = null;
        BufferedReader reader = null;
        int totalNum=0; //总比数
        int no=1000; //总比数
        FileOutputStream file2 = null;
        BufferedWriter writer = null;  
        try {
            File file = new File("D:\\code1.txt");
            // 指定读取文件时以UTF-8的格式读取  
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
            file2  = new FileOutputStream("code.txt", true);
            writer = new BufferedWriter(new OutputStreamWriter(file2,"utf-8"));
            //循环读文件
            while((tempString = reader.readLine()) != null){
                //如果为空行,直接跳过
                if(Strings.isNullOrEmpty(tempString.trim())){
                    logger.info("该行为空行,直接跳过。");
                    continue;  
                }
                String[] tmpStrArr = tempString.split(",",7);
                //  {key:"0005",code:"4210",text:"江西省新建县"},  
                StringBuilder line = new StringBuilder();
                line.append("{key:\"").append(no+totalNum+"").append("\",code:\"")  
                    .append(tmpStrArr[0]+"").append("\",text:\"") 
                    .append(tmpStrArr[1]+"").append("}\",") ; 
                writer.write(line.toString());
                writer.write("\r\n");// 换行
                totalNum++;
            }
            if(totalNum>0){
                writer.flush();
            }
        } catch (Exception e) {
            logger.info(""+e);
        }finally{
            if(reader != null) {
                try {
                    writer.close();
                    reader.close();
                    file2.close();
                } catch (IOException e) {
                    logger.info(""+e);
                }
            }
        }        
    }

 

posted @ 2017-07-14 10:18  不像程序员  阅读(230)  评论(0编辑  收藏  举报