posts - 22,comments - 35,trackbacks - 0
(此为个人学习心得,以后会逐渐完善)

(本例使用的数据库是:MySql)

1.当你用流读取文件或者从数据库读取数据时,取得的字符串的编码要与页面的一致,否则会乱码

例如:

public class FileOperation {

    
//path为文件的全路径
    public static String readFile(String path){
        String templateContent
="";
        
try{
            BufferedReader br
=new BufferedReader(new FileReader(path));
            String temp
=null;
            
while((temp=br.readLine())!=null){
                templateContent
=templateContent+temp+"\n";
            }

            br.close();
        }

        
catch(Exception e){
            System.out.println(
"读取文件出错");
            e.printStackTrace();
        }

        
        
return templateContent;
    }

}


(假设页面的编码为UTF-8)

调用以上函数只需要传递一个完整的文件路径就可以以字符串的形式读取文件.

......

String str
=FileOperation.readFile("d:\11.txt");

......

request.setAttribute("str",str);

......

则页面用requset.getAttribute("str")取得的中文字符将会是乱码.

解决方案:

将上段取中文字符串的代码改成:



String str
=new String(FileOperation.readFile("d:\11.txt").getBytes("UTF-8"));



request.setAttribute(
"str",str);




posted on 2005-12-28 16:16 kelven 阅读(524) 评论(0)  编辑  收藏 所属分类: Struts

只有注册用户登录后才能发表评论。


网站导航: