读书人

黑马软件工程师IO字节流读取键盘录

发布时间: 2013-07-08 14:13:00 作者: rapoo

黑马程序员——IO字节流读取键盘录入和转换流

  ------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------http://www.itheima。com
获取键盘录入,每输入一行就转换成大写输出
当输入over的时候,停止录入
System.out;对应的是标准的输出设备,控制台;
System.in;对应的是标准的输入设备,键盘;


import java.io.*;
class ReadInDemo
{
public static void main(String[] args)throws IOException
{
ReadIn();
}
public static String ReadIn() throws IOException
{
InputStream in=System.in;

StringBuilder sb=new StringBuilder();
while(true)
{
int ch=in.read();

if(ch=='\r')
continue;
if(ch=='\n')
{
String s=sb.toString();
if("over".equals(s))
break;

System.out.print(s.toUpperCase());
sb.delete(0,sb.length());
}
else
sb.append((char)ch);

}
return null;
}
}




从控制台输出一行,发现其原理就是打一行readLine()方法相似。
能不能直接使用readLine()方法呢?

readLine()方法是Reader的子类BufferedReader所提供的方法,操作的是字符流
而键盘录入的read()方法是InputStream的方法,操作的是字节流
那么能不能将字节流转换成字符流使用字符流缓冲区的readLine()方法呢?

InputStreamReader类提供了将字节流转换成字符流


import java.io.*;
class ReadInDemo2
{
public static void main(String[] args)throws IOException
{
//获取键盘录入对象
InputStream in=System.in;

//将字节流对象转换成字符流对象
InputStreamReader isr=new InputStreamReader(in);

//为了提高效率,将字符串进行缓冲区技术高效处理,并使用其readLine()方法
BufferedReader bfd=new BufferedReader(isr);

String len=null;
while((len=bfd.readLine())!=null)
{

if("over".equals(len))
break;

System.out.println(len.toUpperCase());

}
bfd.close();
}

}


字节流
[解决办法]
文字信息用高效缓冲流,readLine;图片文件好像就不适用了

读书人网 >Java相关

热点推荐