一 实战——字节流是数字
1 代码
import java.io.*;
public class BufferDemo {
public static void main( String args[] ) {
BufferedReader buf = null;
// System.in的类型为InputStream,它是字节流
// InputStreamReader是字符流,完成了从字节流到字符流的转换
// 最后用BufferedReader包装,实现高效转换
buf = new BufferedReader(new InputStreamReader(System.in));
String str = null;
while (true) {
System.out.print("请输入数字:");
try {
str = buf.readLine();
} catch (IOException e) {
e.printStackTrace();
}
int i = -1;
try {
i = Integer.parseInt(str);
i++;
System.out.println("输入的数字修改后为:" + i);
break;
} catch (Exception e) {
System.out.println("输入的内容不正确,请重新输入!");
}
}
}
}
2 运行
请输入数字:56
输入的数字修改后为:57
二 实战——字节流是字符
1 代码
import java.io.*;
public class BufferDemo {
public static void main( String args[] ) {
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(System.in));
String str = null;
while (true) {
System.out.print("请输入字符:");
try {
str = buf.readLine();
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println("输入字符是:" + str);
break;
} catch (Exception e) {
System.out.println("输入的内容不正确,请重新输入!");
}
}
}
}
2 运行
请输入字符:中国xian
输入字符是:中国xian