用流进行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 + "个字符");
}
}