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

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


          網站導航:
           
          主站蜘蛛池模板: 敦化市| 连南| 克什克腾旗| 哈尔滨市| 博湖县| 海伦市| 乌拉特中旗| 信丰县| 长武县| 桂林市| 宜昌市| 巩义市| 宿州市| 五原县| 祁连县| 五莲县| 石楼县| 隆昌县| 长汀县| 堆龙德庆县| 韶山市| 多伦县| 新郑市| 西宁市| 德化县| 琼结县| 石景山区| 大埔县| 晴隆县| 洛浦县| 石城县| 长岛县| 西峡县| 石嘴山市| 禄劝| 同德县| 常宁市| 洪湖市| 彰武县| 大港区| 蒲江县|