最近在学习IO流,遇到一个难题,看下面的代码:public static void main(String[] args) throws IOException {
InputStream in=System.in;
int ch=in.read();
System.out.println((char)ch);
}在控制台输入字符a,可以在输出a。但是如果想输入一个汉字,如何输出一个汉字呢?有个要求,就是实现时不能使用InputStreamReader和OutputStreamWriter。IO

解决方案 »

  1.   

    别钻牛角钻了,stream是处理字节的,输入一个汉字,会按编码被解释成几个字节,想构造出来,就把字节再读入构造成字符串就对了String有构造函数:String(bytes[])
      

  2.   


    public static void main(String[] args) {
    InputStream in = System.in;
    byte[] b = new byte[1024];
    int len = -1;

    try {
    while((len = in.read(b)) != -1){
    System.out.println(new String(b,0,len));
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
      

  3.   

    刚些的有些问题,修改了下 public static void main(String[] args) {
    InputStream in = System.in;
    byte[] b = new byte[1024];
    int len = -1;

    try {
    while((len = in.read(b)) != -1){
    System.out.println(new String(b,0,len));
    break;
    }
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    try {
    in.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
      

  4.   

    根据java JDK文档,inputstream 的read 每次读一个byte,返回值是其byte的int表现。
    你只需要吧这些byte存起来即可。下面是示例代码。
    ,import java.io.*;
    import java.util.*;
    public class TestInput
    {
    public static void main(String[] args) throws Exception 
    {
    InputStream in=System.in;
    int ch = 0;
    List<Byte> buff = new ArrayList<Byte>();
    //这里用13 是为了实现用一个回车就读buffer 然后结束的效果
    //正常情况下是返回-1 (ctrl+c)
    while ((ch = in.read())!=13)
    {
    buff.add((byte)ch);
    }
    //toArray只适用于Object Byte 类型
    byte[] buff2 = new byte[buff.size()];
    for (int i = 0;i<buff2.length ;i++ )
    {
    buff2[i] = buff.get(i);
    }
    System.out.println(new String(buff2,"gbk"));
    }
    }
      

  5.   

    import java.io.InputStream;
    import java.io.IOException;
    import java.lang.String;public class test0011 { /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    InputStream in=System.in;
     
    try {
    byte b[] = new byte[1024]; int len = 0;
    int temp=0;          //所有读取的内容都使用temp接收
    while((temp=in.read())!=-1){    //当没有读取完时,继续读取
    b[len]=(byte)temp;
    len++;
    System.out.println(new String(b,0,len)); }
    // System.out.println(b);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }}