import java.io.*;class TestIO
{
public static void main(String[] args) throws Exception
{
byte[] b=new byte[10];
int a =System.in.read(b);
for (int i=0;i<b.length;i++)
System.out.println((char)b[i]);
}
}以上是从控制台接受输入的字符然后打印出来,但是在输入中文的时候
打印出来的却是"??",原因是因为java 中字符都是采用unicode编码,不
管是中文字符还是一个英文字符都占用两个字节,即16位,英文字符在
存贮时都只存贮了低八位,高八位都是空的,而汉字则16位都存满了,
System.in.read()在读取时,好象只取了底八位,所以汉字在读取时实际上
只读了半个汉字!......
不知道说得对不对,请高手指教!!另外有什么方法可以实现可以把汉字完整读
出来呢??(好象只要判断最高位为1就可以了,但具体不知道怎么做啊)
{
public static void main(String[] args) throws Exception
{
byte[] b=new byte[10];
int a =System.in.read(b);
for (int i=0;i<b.length;i++)
System.out.println((char)b[i]);
}
}以上是从控制台接受输入的字符然后打印出来,但是在输入中文的时候
打印出来的却是"??",原因是因为java 中字符都是采用unicode编码,不
管是中文字符还是一个英文字符都占用两个字节,即16位,英文字符在
存贮时都只存贮了低八位,高八位都是空的,而汉字则16位都存满了,
System.in.read()在读取时,好象只取了底八位,所以汉字在读取时实际上
只读了半个汉字!......
不知道说得对不对,请高手指教!!另外有什么方法可以实现可以把汉字完整读
出来呢??(好象只要判断最高位为1就可以了,但具体不知道怎么做啊)
public class TextIo
{
public static void main(String[] args)
{
try
{
//String s = new String(args[0].getBytes("GBK"),"ISO8859_1");
//String s = new String(args[0].getBytes("ISO8859_1"),"GBK");
String s = args[0];
FileWriter fos = new FileWriter("d:\\fos.txt");
PrintWriter pw = new PrintWriter(fos);
pw.print(s);
pw.close();
fos.close();
}catch (IOException e)
{
e.printStackTrace();
}
}
}既然从控制台输入字符串直接用字符流处理即可?
执行上述程序,如果出现乱码则试下上述两条注释语句,每次选择一条,绝有一款适合你
不同的编码。另外,汉字不一定是2个字节,有些是4个字节,而且编码形式
多种多样,如EUC,GBK, GB18030,UTF-8 等等。下面这段代码可以输入输出汉字
byte[] b=new byte[10];
while(true) {
int len = System.in.read(b);
System.out.print(new String(b, 0, len));
}
temp=br.read();
这个可以
// windows系统下,中文字符的默认编码方式是GB2312 byte [] b = new byte [10];
System.in.read (b); for (int i = 0; i < 10; i++){
byte [] buf; if (((int)b [i] & (int)0x80) != 0){
buf = new byte [] {b [i], b [i + 1]}; // 中文字符占两个字节
System.out.println ("b[" + i +"], b[" + (i + 1) + "]: ");
i++;
}
else {
buf = new byte [] {b [i]}; // 一般字符占一个字节
System.out.println ("b[" + i + "]: "); } char c = new String (buf, "GB2312").charAt (0);
if (c != 13 && c != 10 ) {
System.out.println (c);
}
}
}}
public static void main (String [] args) throws Exception {
// windows系统下,中文字符的默认编码方式是GB2312
byte [] b = new byte [10];
System.in.read (b);
// 将b[10]中的每个字节(编码)转换为字符,要用GB2312解码
for (int i = 0; i < 10; i++){
byte [] buf; // 单个字符所占的字节
if (((int)b [i] & (int)0x80) != 0){ // 最高位为1是中文
buf = new byte [] {b [i], b [i + 1]}; // 中文字符占两个字节
System.out.println ("b[" + i +"], b[" + (i + 1) + "]: ");
i++;
}
else { // 否则为一般字符
buf = new byte [] {b [i]}; // 一般字符占一个字节
System.out.println ("b[" + i + "]: ");
}
char c = new String (buf, "GB2312").charAt (0); // 字节解码为字符
if (c != 13 && c != 10 ) { // 不输出回车和换行符
System.out.print (c);
}
System.out.println ();
}
}
}
}
public String trans(String chi){
String result = null;
byte temp [];
try
{
temp = chi.getBytes("ISO8859_1");
result= new String(temp);
}
catch(java.io.UnsupportedEncodingException e)
{
System.out.println(e.toString());
}
return result;
}
}