java 输入输出流将jsp文件生成html,解决乱码问题

该博客主要介绍了如何使用Java通过HTTP请求获取JSP内容并生成HTML文件,同时解决在处理过程中可能出现的中文乱码问题。关键在于设置输入流和输出流的编码为UTF-8,并在HTML文件中添加正确的编码声明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
  * 生成HTMl文件
  */
  BufferedReader in = null;
  URL url1 = null;
  URLConnection urlConn = null;
  try {
   //http://localhost:8080/pertest/admin.go?method=showReportToCustomer&license=
   String strURL = "http://localhost:8080/t/admin.go?method=showReportToCustomer&license="
     + user.getT_license()
     + "&title="
     + URLEncoder.encode(user.getName(), "utf-8");
   
   url1 = new URL(strURL);
   urlConn = url1.openConnection();// 建立http连接
   in = new BufferedReader(new InputStreamReader(urlConn
     .getInputStream(), "UTF-8"));// 设置Encoding,必须设置,否则显示中文会有问题
  } catch (IOException e) {
   log.error(e.getMessage(), e);
  } finally {
   urlConn = null;
   url1 = null;
  }
  
  BufferedWriter out = null;
  try {
   //服务器
   File htmlFile = new File("E:/perTest/UserMsg/"+user.getName()+user.getT_license()+".html");
   //本机 "E:/temp/perTest/UserMsg/"+user.getName()+user.getT_license()+".html");
   htmlFile.createNewFile();
   out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));// 设置Encoding
   // 写HTMl文件
   while (in.ready()) {
    out.write(in.readLine());
   }

  } catch (IOException e) {
   log.error(e.getMessage(), e);
  } finally {
   try {
    in.close();
    out.close();
   } catch (IOException e) {
    log.error(e.getMessage(), e);
   }
  }

解决乱码,原因是没有设置html编码格式

  1、设置 HTML 页面编码格式为 UTF-8

  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

  2、设置 HTML 页面编码格式为中文
  <meta http-equiv="content-language" content="zh-CN" />

  3、设置 JSP 页面编码格式为 UTF-8

  <%@ page contentType="text/html;charset=UTF-8" %>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值