如何在读写文件时指定文件编码

 /**
     * 插入单条模板记录
     * 
     * @param vo  模板VO对象
     * @return 若添加成功,返回新生成的主键对象OID
     * @throws IOException 读写文件失败时会抛出此异常
     */
    public OID insert(EwpTemplate ewpTemplateVO) throws Exception {
        
        //模板VO保存到了数据库
        getDao().insert(ewpTemplateVO);
        
        //把模板内容保存到文件系统
        String filepath = ewpTemplateVO.getFilepath();          //文件路径
        String directory = ewpTemplateVO.getDirectory();      //文件目录
        OutputStreamWriter fw = null;
        BufferedWriter bw = null;
        try {
            // 如果目录不存在则创建目录,不创建目录直接创建文件会抛出FileNotFoundException
            File dir = new File(directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 保存模板内容文件
            fw = new OutputStreamWriter(new FileOutputStream(new File(filepath)), "UTF-8");
            bw = new BufferedWriter(fw);
            bw.write(ewpTemplateVO.getTemplate_content());
        } catch (IOException e) {
            throw e;
        } finally {
            if (bw != null) {
                bw.close();
            }
            if (fw != null) {
                fw.close();
            }
        }
        return new OID(1);
    }
   /**
     * 按UTF-8编码读取文件
     */
    public void readFile() throws Exception{
        String filepath = ".";
        File file = new File(filepath);
        if(file != null && file.exists()){
            InputStreamReader reader =   null;
            BufferedReader br = null;
            try{
                reader = new InputStreamReader(new FileInputStream(file),"UTF-8");
                br = new BufferedReader(reader);  
                StringBuffer sb = new StringBuffer();
                String str = null;
                do{
                    str = br.readLine();
                    if(str != null){
                        sb.append(str+"<br/>");
                    }
                }while(str!=null);
                System.out.println(str);
            }finally{
                if(br != null){
                    br.close();
                }
                if(reader != null){
                    reader.close();
                }
            }
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值