posts - 22,comments - 35,trackbacks - 0
          (此為個人學(xué)習(xí)心得,以后會逐漸完善)

          (本例使用的數(shù)據(jù)庫是:MySql)

          1.當(dāng)你用流讀取文件或者從數(shù)據(jù)庫讀取數(shù)據(jù)時,取得的字符串的編碼要與頁面的一致,否則會亂碼

          例如:

          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;
              }

          }


          (假設(shè)頁面的編碼為UTF-8)

          調(diào)用以上函數(shù)只需要傳遞一個完整的文件路徑就可以以字符串的形式讀取文件.

          ......

          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 閱讀(543) 評論(0)  編輯  收藏 所屬分類: Struts

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 松滋市| 寿宁县| 佛坪县| 上虞市| 共和县| 惠州市| 新疆| 许昌市| 原平市| 安丘市| 韩城市| 垣曲县| 通化县| 资溪县| 松原市| 绥中县| 南和县| 阳城县| 仁布县| 碌曲县| 西林县| 来安县| 东城区| 汉中市| 永春县| 镇沅| 仁寿县| 忻州市| 梓潼县| 白沙| 武城县| 华蓥市| 屏边| 温州市| 娄底市| 东兴市| 遵化市| 鹿泉市| 晋城| 曲阳县| 高雄市|