posts - 1,  comments - 25,  trackbacks - 0




          對于我們常用的GBK中,英文是占用1個字節,中文是2個

            對于UTF-8,英文是1個,中文是3個

            對于Unicode,英文中文都是2個

            Java的流操作分為字節流和字符流兩種。

          2.3 Java 中相關實現方法

          字符串類 String 中的內容是 UNICODE 字符串:

          // Java 代碼,直接寫中文
          String
           string = "中文123";

          // 得到長度為 5,因為是 5 個字符
          System.out.println(string.length());

          字符串 I/O 操作,字符與字節轉換操作。在 Java 包 java.io.* 中,以“Stream”結尾的類一般是用來操作“字節串”的類,以“Reader”,“Writer”結尾的類一般是用來操作“字符串”的類。

          // 字符串與字節串間相互轉化

          // 按照 GB2312 得到字節(得到多字節字符串)

          byte
           [] bytes = string.getBytes("GB2312");

          // 從字節按照 GB2312 得到 UNICODE 字符串
          string = new String(bytes, "GB2312");

          // 要將 String 按照某種編碼寫入文本文件,有兩種方法:

          // 第一種辦法:用 Stream 類寫入已經按照指定編碼轉化好的字節串

          OutputStream os = new FileOutputStream("1.txt");
          os.write(bytes);
          os.close();

          // 第二種辦法:構造指定編碼的 Writer 來寫入字符串
          Writer ow = new OutputStreamWriter(new FileOutputStream("2.txt"), "GB2312");
          ow.write(string);
          ow.close();

          /* 最后得到的 1.txt 和 2.txt 都是 7 個字節 */

          如果 java 的源程序編碼與當前默認 ANSI 編碼不符,則在編譯的時候,需要指明一下源程序的編碼。比如:

          E:\>javac -encoding BIG5 Hello.java

          以上需要注意區分源程序的編碼與 I/O 操作的編碼,前者是在編譯時起作用,后者是在運行時起作用。

          IO分兩種流 

          字節流 InputStream OutputStream 

          字符流 Reader Writer 

          他們都是抽象類 

          具體實現 
          字節流 FileInputStream FileOutputStream 
          字符流 FileReader FileWriter  

                 字符流處理的單元為2個字節的Unicode字符,分別操作字符、字符數組或字符串,而字節流處理單元為1個字節, 操作字節和字節數組。所以字符流是由Java虛擬機將字節轉化為2個字節的Unicode字符為單位的字符而成的,所以它對多國語言支持性比較好!如果是 音頻文件、圖片、歌曲,就用字節流好點,如果是關系到中文(文本)的,用字符流好點. 
               所有文件的儲存是都是字節(byte)的儲存,在磁盤上保留的并不是文件的字符而是先把字符編碼成字節,再儲存這些字節到磁盤。在讀取文件(特別是文本文件)時,也是一個字節一個字節地讀取以形成字節序列. 
                字節流可用于任何類型的對象,包括二進制對象,而字符流只能處理字符或者字符串; 2. 字節流提供了處理任何類型的IO操作的功能,但它不能直接處理Unicode字符,而字符流就可以。 


          字節流轉換成字符流可以用 InputSteamReader OutputStreamWriter 

          轉換成BufferdReader BufferedWriter 他們具有緩沖區 

          例如:讀取文件 從字節流輸入到字符流輸入 
          定義一個字節流: 
          FileInputStream fileInputStream = new FileInputStream("d:/text.txt"); // 定義一個指 

          向D:/TEXT.TXT 的字節流 

          InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); 
          //字節流轉換成InputStreamReader 
          BufferedReader bufferedReader = new BufferedReader(inputSteamReader); 
          //InputStreamReader 轉換成帶緩存的bufferedReader 

          可以把讀出來的內容賦值給字符 

          String ss = new String(); 
          String s; 
          while((s = bufferedReader.readLine())!=null){ 
          ss += s; 


          例如:寫入文件 從字節流輸出到字符流輸出 

          FileOutputStream fileOutputStream = new FileOutputStream("d:/text.txt"); //定義一個 

          指向D:/TEXT.TXT文件 

          OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); 

          BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); 

          bufferedWriter.write(s); 

          bufferedWriter.close(); 
          outputStreamWriter.close(); 
          fileOutputStream.close(); 


          例程: 
               將字符串轉化為字節流#region 將字符串轉化為字節流 
                  /**//// <summary> 
                  /// 將字符串轉化為字節流 
                  /// </summary> 
                  /// <param name="_Source">字串</param> 
                  /// <returns>字節流</returns> 
                  public static byte[] String2Bytes(string strSource) 
                  { 
                      System.IO.MemoryStream   memoryStream=new   System.IO.MemoryStream();   
                      System.IO.BinaryWriter   binaryWriter=new   System.IO.BinaryWriter(memoryStream);   
                      binaryWriter.Write( strSource ); 
                      byte[]   buffer=memoryStream.GetBuffer(); 
                      return buffer;    
                  } 
                  #endregion 

                  
                  將字節流轉化為字符串#region 將字節流轉化為字符串 
                  /**//// <summary> 
                  /// 將字節流轉化為字符串 
                  /// </summary> 
                  /// <param name="bytData">字節流</param> 
                  /// <returns>字串</returns> 
                  public static string Bytes2String(byte[] bytData) 
                  { 
                      //字節流->字符串   
                      System.IO.MemoryStream   memoryStream2 = new   System.IO.MemoryStream(bytData);   
                      System.IO.BinaryReader   binaryReader = new   System.IO.BinaryReader(memoryStream2);   
                      string   s2=binaryReader.ReadString();   
                      return s2; 
                  } 
                  #endregion
          posted on 2010-08-16 17:16 Daniel 閱讀(1790) 評論(1)  編輯  收藏 所屬分類: CoreJava

          FeedBack:
          # re: Java的字符流和字節流
          2011-12-23 20:39 | mlzry0612
          留下備忘!
          文件拷貝:
          Java代碼
          public static void copyFile(File src,File dest) throws Exception{
          try {
          // Create channel on the source
          FileChannel srcChannel = new FileInputStream(src).getChannel();

          // Create channel on the destination
          FileChannel dstChannel = new FileOutputStream(dest).getChannel();

          // Copy file contents from source to destination
          dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

          // Close the channels
          srcChannel.close();
          dstChannel.close();
          } catch (IOException e) {
          }

          }

          文件重命名:
          Java代碼
          public static renameFile(File src,String newFilename)throws Exception{
          src.renameTo(new File(newFilename));//請寫明完整路徑
          }

          將文件讀成字符串:
          Java代碼
          public static String ReadFileToString(String pathAndFilename) {
          StringBuffer str = new StringBuffer();
          BufferedReader in = null;
          File inputFile = null;
          try {
          inputFile = new File(pathAndFilename);
          in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "utf-8"));
          String line = null;
          str = new StringBuffer((int) inputFile.length());
          while ((line = in.readLine()) != null) {
          str.append(line);
          }
          in.close();
          }
          catch (FileNotFoundException e2) {
          try {
          if (!new File(inputFile.getParent()).exists())
          new File(inputFile.getParent()).mkdirs();
          inputFile.createNewFile();
          }
          catch (IOException e) {
          e.printStackTrace();
          }
          }
          catch (IOException e3) {
          e3.printStackTrace();
          }
          return str.toString();
          }   回復  更多評論
            
          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          常用鏈接

          留言簿(3)

          隨筆檔案

          文章分類

          文章檔案

          相冊

          搜索

          •  

          最新評論

          主站蜘蛛池模板: 广州市| 贵定县| 沙坪坝区| 鹿泉市| 深泽县| 翁牛特旗| 凤庆县| 建宁县| 灵川县| 穆棱市| 黔江区| 高雄市| 唐河县| 宝兴县| 东兰县| 山阳县| 建水县| 饶河县| 隆回县| 南投县| 长治县| 乌海市| 明水县| 黎城县| 平凉市| 平乐县| 黄浦区| 普格县| 莱芜市| 林州市| 隆昌县| 新宁县| 南宫市| 黔东| 桂林市| 崇明县| 淄博市| 乌鲁木齐市| 蒙自县| 永靖县| 虎林市|