JavaSE进阶
13.2.6 标准输入/输出流
标准输入/输出流
- in和System.out分别代表了系统标准的输入和输出设备
- 默认输入设备是键盘,输出设备是显示器
- in的类型是InputStream
- out的类型是PrintStream,其是OutputStream的子类FilterOutputStream 的子类
- 通过System类的setIn,setOut方法对默认设备进行改变。
- public static void setIn(InputStreamin)
- public static void setOut(PrintStreamout)
例 题
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,直至当输入“e”或者“exit”时,退出程序。
System.out.println("请输入信息(退出输入e或exit):");
// 把"标准"输入流(键盘输入)这个字节流包装成字符流,再包装成缓冲流
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = null;
try {
// 读取用户输入的一行数据 --> 阻塞程序
while ((s = br.readLine()) != null) {
if (s.equalsIgnoreCase("e") || s.equalsIgnoreCase("exit")) {
System.out.println("安全退出!!");
break;
}
// 将读取到的整行字符串转成大写输出
System.out.println("-->:" + s.toUpperCase());
System.out.println("继续输入信息");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close(); // 关闭过滤流时,会自动关闭它包装的底层节点流
}
} catch (IOException e) {
e.printStackTrace();
}
}
13.2.6.1练习
Create a program named MyInput.java: Contain the methods for reading int, double, float, boolean, short, byte and String values from the keyboard
例:
Scanner s = new Scanner(System.in);
s.nextInt();
s.next();
13.2.7 打印流
- 实现将基本数据类型的数据格式转化为字符串输出
- 打印流:PrintStream和PrintWriter
- 提供了一系列重载的print和println方法,用于多种数据类型的输出
- PrintStream和PrintWriter的输出不会抛出异常
- PrintStream和PrintWriter有自动flush功能
- out返回的是PrintStream的实例
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
PrintStream ps = new PrintStream(fos, true);
if (ps != null) { // 把标准输出流(控制台输出)改成文件
System.setOut(ps);
}
for (int i = 0; i <= 255; i++) { // 输出ASCII字符
System.out.print((char) i);
if (i % 50 == 0) { // 每50个数据一行
System.out.println(); // 换行
}
}
ps.close();