[Java基礎]用流進行byte位元組流的讀寫
阿新 • • 發佈:2019-02-03
用流進行byte位元組流的讀寫
import java.io.ByteArrayInputStream; public class StringByteCount { static String str = "This 測試1"; int countStringByte(String str) { int count = 0; ByteArrayInputStream sin = new ByteArrayInputStream(str.getBytes()); int c; byte word[] = new byte[2]; int i = 0; try { while ((c = sin.read()) != -1) { System.out.println("讀到一個位元組:" + c); if (c == 0) { continue; } if (c > 0 && c <= 127) { count++; continue; } if (c > 127) { word[i] = (byte) c; if (i == 1) { System.out.println("讀到一個漢字:" + new String(word)); i = 0; count++; } else i++; } } } catch (Exception e) { e.printStackTrace(); } return count; } public static void main(String[] args) { StringByteCount sb = new StringByteCount(); int sum = sb.countStringByte(str); System.out.println("總共" + sum + "個字元"); } }