举例:test.txt文件内容是:
中ab国cd,.?因为要对读取的字节做一些计算处理,所以采用InputStream(new FileInputStream("test.txt"));来读取文件,读取英文与标点符号时通过(char)ch可以转换成可见字符.但当读取到中文时(中文是占用两个字节)..这个时候如何确定读的是中呢?
中ab国cd,.?因为要对读取的字节做一些计算处理,所以采用InputStream(new FileInputStream("test.txt"));来读取文件,读取英文与标点符号时通过(char)ch可以转换成可见字符.但当读取到中文时(中文是占用两个字节)..这个时候如何确定读的是中呢?
c="中"; if(c>='\u4e00' && c<='\u9fbf'){
System.out.println("是汉字");
}else{
System.out.println("不是汉字");
}
String s="外ty过56"; for(int i=0; i<s.length(); i++) {
System.out.printf("%c -- ", s.charAt(i));
boolean b = (s.charAt(i) + "").matches("[\u4e00-\u9faf]");
if(b)
System.out.println("是汉字");
else
System.out.println("不是汉字");
}
}
思路就是比较汉字的高位,以前做过一个类似的东西,现在忘了。
这么匹配会不会很慢
例子文件:
通过"记事本"程序创建的文件(ANSI)格式:
test.txt
内容:
a b c d 中 国 , . ?
对应的16进制码:61 62 63 64 d6d0 b9fa 2c 2e 3fint ch;
while((ch = in.read()) != -1)
{
System.out.println((char)ch));//当是汉字时,这样简单的输出就不对了.
}
我要通过java一个字节一个字节的读取数据(8bit),读到a时通过(char)ch可以转换成可见字符,因为char是16bit的,底8bit保存61,,所以应该是0061(没测试过,想着应该是)输出是没有问题的..但当是汉字'中'时,如果单独的当一个字节处理d6=-42再转换过来(char)ch = \uffd6输出的就是乱码..应该把d6d0合着输出(怎么合着输出,占时不管它)...读到d6时怎么知道它是个汉子呢?
* @param args
*/
public static void main(String[] args) {
char c = '中';
if(c>='\u4e00' && c<='\u9fbf')
System.out.println("是汉字");
else
System.out.println("不是汉字"); }}
if(b > 0x7f) {
再读取一个字节
}
判断高位
{
int r=2;
for(int i=0;i<Str.length();i++)
{
char ch=Str.charAt(i);
short chint=(short)ch;
if((chint>=48)&&(chint<=57))
{
//这个字符是数字
}
else
if(((chint>=91)&&(chint<=122))||((chint>=65)&&(chint<=90))||(chint==95))
{
//这个字符是英文或者是"_"
r=1;
}
else
if(((chint&0XFF00)>>8)>0)
{
//这个字符是中文
r=0;
}
else
{
//这个字符是特殊字符
r=-1;
}
}
return r;
}
// \w A word Character[a-zA-Z_0-9]
// \p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Pattern p=Pattern.compile("[\\w]|[\\p{Punct}]");
Matcher m=p.matcher(String.valueOf(c));
return m.matches();
}