小实验:读取键盘输入
System类中的in是InputStream对象,对应的标准输入设备是键盘;
System类中的out是PrintStream对象,对应的是标准输出设备是控制台。
import java.io.*;
class TestKeyInput
{
public static void main(String[] args) throws IOException
{
InputStream in=System.in;
int a=in.read();// read()方法是阻塞式方法,如果没有读到数据就会等待。
int b=in.read();
int c=in.read();
int d=in.read();
int e=in.read();
//反斜杠是\r\n,在ASCII表里是13 和10
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
}
}
练习:
需求:通过键盘录入数据,当录入一行数据后 ,就将该行数据进行打印,如果录入的数据是over,那么停止录入
方式一:
import java.io.*;
class TestKeyInput2
{
public static void main(String[] args) throws IOException
{
/*InputStream in=System.in;
int a=in.read();// read()方法是阻塞式方法,如果没有读到数据就会等待。
int b=in.read();
int c=in.read();
int d=in.read();
int e=in.read();
//反斜杠是\r\n,在ASCII表里是13 和10
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);*/
InputStream in=System.in;
StringBuilder sb=new StringBuilder();
int b=0;
while(true)
{
b=in.read();
if(b==13)
continue;
if(b==10)
{
if(sb.toString().equals("over"))
break;
System.out.println(sb.toString());
sb.delete(0,sb.length());
}
else
{
sb.append((char)b);
}
}
}
}
方式二:
通过刚才的键盘录入一行数据并打印,发现其实就是读一行数据的原理。
也就是readLine方法。
能不能直接使用readLine方法来完成键盘录入的一行数据的读取呢?
readLine方法是字符流BufferedReader类中的方法。
而键盘录入的read方法是字节流InputStream的方法。
那么能不能将字节流转成字符流在使用字符流缓冲去的readLine方法呢?
答案是肯定的!
这就用到了Reader的一个子类:InputStreamReader
InputStreamReader 是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。
构造方法:
InputStreamReader(InputStream in)
创建一个使用默认字符集的 InputStreamReader。
readLine()方法是BufferedReader类的方法。所以将字节流转成字符流之后,要使用BufferedReader进行包装。
import java.io.*;
class TestKeyInput3
{
public static void main(String[] args) throws IOException
{
InputStream in=System.in;
InputStreamReader isr=new InputStreamReader(in);
BufferedReader br=new BufferedReader(isr);
String line=null;
while((line=br.readLine())!=null)
{
if(line.equals("over"))
break;
System.out.println(line);
}
br.close();
}
}
键盘录入最常见的写法:
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
写入转换流
OutputStreamWriter
OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节。
构造方法:
OutputStreamWriter(OutputStream out)
创建使用默认字符编码的 OutputStreamWriter。
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));