使用字节流生成文件乱码

  • 原来的代码:
    public void createHtmlFile(InfoPublishForm infoPublishForm){
        String data = infoPublishForm.getContent().replaceAll("src=\"/DNSFile/Img/news/",
                "src=\"../Img/news/");
        String path=AppContext.current().getConfig().getProperty("runtime.attchment.rootPath")+
                AppContext.current().getConfig().getProperty("runtime.cdn.news.rootPath")+infoPublishForm.getNewsid()+".html";
        String dirPath=AppContext.current().getConfig().getProperty("runtime.attchment.rootPath")+
                AppContext.current().getConfig().getProperty("runtime.cdn.news.rootPath");

        BufferedReader br = null;
        PrintWriter out = null;
        File dir=new File(dirPath);
        File html=new File(path);
        try {
            if (!dir.exists()) {
                dir.mkdirs();
            }
            if(!html.exists()){
                html.createNewFile();
            }
            byte bytes[]=new byte[512];
            bytes=data.getBytes(); 
            int b=data.length(); 
            FileOutputStream fos=new FileOutputStream(html);
            fos.write(bytes,0,b);
            fos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        pushToCdn(path);
    }
  • 生成的文件:


    image.png

    原因:将字符串转为字节流的时候没有设置编码,修改

  bytes=data.getBytes("UTF-8"); 
image.png

解决了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 那是一个混沌的世界 伤口定格在消化道 距离心口半余寸 恒河上的日出亦是东方 岸边没有焚尸炉 敲碎脑壳是为了释放灵魂...
    炎炎冬日阅读 1,209评论 8 30
  • 《张家界组诗·之三》 《七律 · 十里画廊》 十里画廊茫苍苍, 峰林石笋冲天状。 千姿百态竟妖娆, 地质奇观世无双...
    湘南一夫阅读 327评论 3 5
  • 今天是我第一天加入简书,想要锻炼一下自己的写作能力。 我现在是一名在校的大学生,有对文学的热爱,却没有去付出。 我...
    wuli果子酱阅读 292评论 0 0