关于用java生成html文件后编码问题的小节

在上传html文件的时候,一定要指定写出的io流的编码,这样就可以生成指定编码的html文件。

在用java读取的时候用普通的字节流就可以了,因为他的编码就是默认的html文件的编码。

以下是代码:

/**
     * 写一个字符串到指定文件中
     *
     * @param fullFileName
     *            完整的文件路径
     * @param content
     *            文件内容字符串
     */
    private void writeString2File(String fullFileName, String content) {
        String rootpath = getProperties("rootpath");
        String absolutePath = rootpath + fullFileName;
        String headHtmlStr = "<html><head><meta http-equiv='content-type' content='text/html;      charset=UTF-8'></head><body>";
        String bodyHtmlStr = "</body></html>";
        content = headHtmlStr + content + bodyHtmlStr;
        File file = new File(absolutePath);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        PrintWriter outFile = null;
       
        try {
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos,"utf-8");//这里可以生成编码是utf-8的html的文件
            outFile = new PrintWriter(osw);
            outFile.write(content);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

 

/**
     * 读取二进制文件的内容(pdf,word,jpg),并以流的方式返回到页面
     * @param absolutePath
     * @param os
     * @throws Exception
     */
    private void readBinFile(String absolutePath, OutputStream os) throws Exception{
        File file = new File(absolutePath);
            FileInputStream fileIn = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fileIn.read(buffer)) > 0)
        {
            os.write(buffer, 0, len);
        }
           
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
       if (fileIn != null) {
        try {
            fileIn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
           
    }

读取文件的时候就不用指定io流的编码了,用html默认的编码就可以了。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值