高分!FileOutputStream类write成UTF-8编码时出现乱码
先说说我的情况:
我以前一直是用GBK编码来做WEB开发,这次我用了UTF-8,就出现了不少问题。
下面的代码是我用来WEB开发时生成静态页面的,如果是GBK编码时,没有任何问题,生成的页面不会出现乱码的情况。但是现在我用的编码是UTF-8,就出现了乱码,我怎样转换都转换不过来。只能求教高手了!
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class PageStatic {
/**
* 将信息转化为静态html
* @param sFilePath 动态信息访问URL
* @param sSavePath 存储为静态文件的目录
* @param sHtmlFile 生成的静态文件名,可以按信息的唯一ID+.html命名
* @throws IOException
*/
public static void updateStatic(String sFilePath,String sSavePath,String sHtmlFile) throws IOException {
PageStatic ru = new PageStatic();
String filePath = ru.getClass().getResource("/com/PageStatic/PageStatic.class").getPath().toString(); //取得项目根目录
filePath = filePath.substring(1, filePath.indexOf("WEB-INF")-1);
int HttpResult;
String SavePath = filePath + sSavePath; //保存路径
URL url=new URL(sFilePath);
URLConnection urlconn=url.openConnection(); //抽象类 URLConnection 是所有类的超类,它代表应用程序和 URL 之间的通信链接,通过在 URL 上调用 openConnection 方法创建连接对象
urlconn.connect(); //使用 connect 方法建立到远程对象的实际连接
HttpURLConnection httpconn=(HttpURLConnection)urlconn; //每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络
HttpResult=httpconn.getResponseCode(); //getResponseCode可以从 HTTP 响应消息获取状态码
if(HttpResult!=HttpURLConnection.HTTP_OK) {
} else {
InputStreamReader isr = new InputStreamReader(httpconn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
if(!SavePath.endsWith("/")) {
SavePath+="/";
}
FileOutputStream fout = new FileOutputStream(SavePath+sHtmlFile);
while ((inputLine = in.readLine()) != null)
{
fout.write((inputLine + (char)13 + (char)10).getBytes());
}
in.close();
fout.close();
}
}
}