在上传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默认的编码就可以了。