根据文件的系统路径进行读取不会出现乱码,如果根据url(如:http://www.juapk.com/index.html)读取,一定要设置好服务器的编码格式,要不然会出现乱码的。
下面是在网上找到的一个例子:
import java.io.*;
import java.awt.event.*;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class JEditorPaneTest {
public static void main(String[] args) {
JEditorPane editPane = null;
try {
//System.setProperty("file.encoding", "UTF-8");//系统编码格式
File file = new File("src/test.html");
String str = file.getAbsolutePath();//取得文件位置的绝对路径
str = "file:" + str;//将绝对路径合成一完整的输入字符串
editPane = new JEditorPane();//构造一个空的JEditorPane
editPane.setEditable(false);
//现在还不知道下边两行代码的作用
editPane.setContentType("text/html;charset=utf-8");
editPane.putClientProperty("charset", "utf-8");
editPane.setPage(str);
} catch (IOException ioe) {
ioe.printStackTrace(System.err);
System.exit(0);
}
editPane.setEditable(false);
JFrame f = new JFrame("JEditorPaneTest");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200, 200);
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
一个test.html页面(注意下边的文件保存的时候选择字符集为utf-8,要不然也会出现乱码的):<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
TODO write:中国
</body>
</html>