1. 标准的输入输出流

System.in:标准的输入流,默认从键盘输入 System.out:标准的输出流,默认从控制台输出

修改默认的输入和输出行为: System类的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定输入和输出的流

2. 打印流

PrintStream 和 PrintWriter

说明:

提供了一系列重载的print()和println()方法,用于多种数据类型的输出 System.out返回的是PrintStream的实例

3. 数据流

DataInputStream 和 DataOutputStream 作用:用于读取或写出基本数据类型的变量或字符串

示例代码:

  1. /*
  2. 练习:将内存中的字符串、基本数据类型的变量写出到文件中。
  3. 注意:处理异常的话,仍然应该使用try-catch-finally.
  4. */
  5. @Test
  6. public void test3() {
  7. DataOutputStream dos = null;
  8. try {
  9. dos = new DataOutputStream(new FileOutputStream("data.txt"));
  10. dos.writeUTF("小明");
  11. dos.flush();
  12. dos.writeInt(23);
  13. dos.flush();
  14. dos.writeBoolean(false);
  15. dos.flush();
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. } finally {
  19. try {
  20. if (dos != null)
  21. dos.close();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }
  1. /*
  2. 将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
  3. 注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
  4. */
  5. @Test
  6. public void test4() {
  7. DataInputStream dis = null;
  8. try {
  9. dis = new DataInputStream(new FileInputStream("data.txt"));
  10. String name = dis.readUTF();
  11. int age = dis.readInt();
  12. boolean isMale = dis.readBoolean();
  13. System.out.println("name:" + name);
  14. System.out.println("age:" + age);
  15. System.out.println("isMale:" + isMale);
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. } finally {
  19. try {
  20. if (dis != null)
  21. dis.close();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }