header detail 1
header detail 2
世界杯热身赛_世界杯赛程 - toption-intl.com
世界杯热身赛_世界杯赛程 - toption-intl.com

Java IO流系列⑥ -- 打印流,数据流

Home 2025-06-19 09:51:34 Java IO流系列⑥ -- 打印流,数据流
世界杯乌龙球

目录

打印流概述

打印流的应用练习

数据流概述

数据流的应用练习

打印流概述

实现将基本数据类型的数据格式转化为字符串输出 打印流:

PrintStream

PrintWriter

①这两个流均为输出流。 ②提供了一系列重载的print()和println()方法,用于多种数据类型的输出 ③PrintStream和PrintWriter的输出不会抛出IOException异常 ④PrintStream和PrintWriter有自动flush功能

打印流的应用练习

任务:将255个ASCII码值对应的字符打印到一个文件当中 代码实现:

@Test

public void test2() {

PrintStream ps = null;

try {

FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));

// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)

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(); // 换行

}

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} finally {

if (ps != null) {

ps.close();

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

数据流概述

方便地操作Java语言的基本数据类型和String的数据 数据流有两个类:(用于读取和写出基本数据类型、String类的数据)

DataInputStream

DataOutputStream

分别“套接”在 InputStream 和 OutputStream 子类的流上 DataInputStream中的方法: DataOutputStream中的方法: 将上述的方法的read改为相应的write即可

数据流的应用练习

练习:①将内存中的字符串、基本数据类型的变量写出到文件中。 ②将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。

@Test

public void test3() throws IOException {

//1.

DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));

//2.

dos.writeUTF("Tom");

dos.flush();//刷新操作,将内存中的数据写入文件

dos.writeInt(23);

dos.flush();

dos.writeBoolean(true);

dos.flush();

//3.

dos.close();

}

@Test

public void test4() throws IOException {

//1.

DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));

//2.

String name = dis.readUTF();

int age = dis.readInt();

boolean isMale = dis.readBoolean();

System.out.println("name = " + name);

System.out.println("age = " + age);

System.out.println("isMale = " + isMale);

//3.

dis.close();

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!处理异常的话,仍然应该使用try-catch-finally.

文章来源: blog.csdn.net,作者:十八岁讨厌编程,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/zyb18507175502/article/details/122493813

Post navigation

  • Prev Post 罗斯5开箱测评 罗斯5实战性能怎么样
Copyright © 2088 世界杯热身赛_世界杯赛程 - toption-intl.com All Rights Reserved.
友情链接