January 13, 2009
長期在寫JAVA程式就會知道中文亂碼問題是一定會碰到的,像最近我在寫JSP有關於讀檔、寫檔的部分,就有那種網頁是UTF8編碼,而要讀寫的檔是BIG5或其他編碼,而導至頁面程現亂碼的現像。
處理方法很簡單,反正萬變不離其宗,但是還是記一下以備不時之需。
JSP頁的編碼為UTF8:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
讀檔:
<%
String content = "";
File file = new File("test.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
content += dis.readLine()+"\r\n";
}
fis.close();
bis.close();
dis.close();
content = new String(content.getBytes("8859_1"),"BIG5");
} catch (FileNotFoundException e) {
out.println(e.toString());
} catch (IOException e) {
out.println(e.toString());
}
%>
寫檔:
<%
String ccontent = request.getParameter("content");
FileOutputStream fos;
DataOutputStream dos;
try {
File file= new File("test.txt");
fos = new FileOutputStream(file);
byte data[] = new String(content.getBytes("8859_1")).getBytes("BIG5");
fos.write(data);
fos.close();
} catch (IOException e) {
out.println(e.toString());
}
%>
處理方法很簡單,反正萬變不離其宗,但是還是記一下以備不時之需。
JSP頁的編碼為UTF8:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
讀檔:
<%
String content = "";
File file = new File("test.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
content += dis.readLine()+"\r\n";
}
fis.close();
bis.close();
dis.close();
content = new String(content.getBytes("8859_1"),"BIG5");
} catch (FileNotFoundException e) {
out.println(e.toString());
} catch (IOException e) {
out.println(e.toString());
}
%>
寫檔:
<%
String ccontent = request.getParameter("content");
FileOutputStream fos;
DataOutputStream dos;
try {
File file= new File("test.txt");
fos = new FileOutputStream(file);
byte data[] = new String(content.getBytes("8859_1")).getBytes("BIG5");
fos.write(data);
fos.close();
} catch (IOException e) {
out.println(e.toString());
}
%>




















