java创建.html或.text文件后中文乱码问题

来源:互联网 发布:mac安装第三方软件 编辑:程序博客网 时间:2024/06/06 13:02

今天碰到一个问题,在创建.html和.text时插入的中文全部乱码

现在解决了,贴下代码

这样写会使中文乱码>>应为没有指定字符编码

/**      * 创建一个文件>>中文会乱码      * @param content      * @param path      * @return      */     public static String CreateFile(String content,String path) {           byte[] b=content.getBytes();           BufferedOutputStream stream = null;           File file = null;           try {               file = new File(path);               FileOutputStream fstream = new FileOutputStream(file);               stream = new BufferedOutputStream(fstream);               stream.write(b);           } catch (Exception e) {               e.printStackTrace();           } finally {               if (stream != null) {                   try {                       stream.close();                   } catch (Exception e) {                       e.printStackTrace();                   }               }           }           return path;     }

后改成>>>其中指定了utf-8就解决了

 /**      * 创建一个文件>>>>解决中文乱码      * @param content      * @param path      * @return      */     public static String CreateFiles(String content,String path) {            File file = null;           try {               file = new File(path);               BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));             bw.write(content);             bw.flush();             bw.close();         } catch (Exception e) {               e.printStackTrace();           }           return path;     }

PS:在生成html时,在拼接代码的时候记得指定字符编码格式

 stringHTML.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">")
原创粉丝点击