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

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


          網站導航:
           
          主站蜘蛛池模板: 武冈市| 天门市| 肇州县| 和平区| 遂溪县| 平罗县| 吴江市| 资兴市| 蚌埠市| 佛山市| 临武县| 武川县| 南川市| 金山区| 巴彦淖尔市| 安顺市| 常山县| 巴楚县| 宁都县| 区。| 承德县| 遂宁市| 麦盖提县| 九江市| 莒南县| 清远市| 蓬溪县| 古浪县| 新宾| 怀来县| 饶阳县| 邢台县| 井陉县| 昌吉市| 宜川县| 安宁市| 微山县| 庆元县| 东乡族自治县| 康乐县| 汤阴县|