键盘输入的内存流实现

刚开始学JAVA,开个博客记一下个人的小程序笔记。欢迎各位大牛提出建议和指出错误!

学习到io编程时看到书上的一个例子,

public class Tree {

    public static void main(String arg[]) throws Exception {
        InputStream input = System.in;
        StringBuffer str = new StringBuffer();
        System.out.println("input data:");
        int temp = 0;
        while((temp = input.read()) != -1) {
            if(temp == '\n') {
                break;
            }
            str.append((char)temp);
        }
        input.close();
        System.our.println("data: ");
        System.out.println("data:" + str);
    }

这个是实现键盘输入的一个例程,这个程序在输入英文时没有问题,但当输入中文时会出现乱码,因为每次只读一个字节造成编码错误。

input data:
world execution 世界
data:world execution ????

我自己尝试着改了一下,利用toByteArray()直接转成String来输出

public class Test {
    public static void main(String arg[]) throws Exception {
        InputStream input = System.in;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        System.out.println("input data:");
        int temp = 0;
        while((temp = input.read()) != '\n') {
            output.write(temp);
        }
        String str = new String(output.toByteArray());
        input.close();
        output.close();
        System.out.println("data: ");
        System.out.println(str);
    }
}

输出结果:

input data:
world execution 世界
data: 
world execution 世界

猜你喜欢

转载自blog.csdn.net/shibuyarin/article/details/78482100