
1.数据流
1.1<br /> DataInputStream 和 DataOutputStream<br /> 1.2作用:<br /> 用于读取或写出基本数据类型的变量或字符串<br /> 练习:将内存中的字符串、基本数据类型的变量写出到文件中
package com.atguigu.java2;import org.junit.Test;import java.io.*;/*** @author Dxkstart* @create 2021-05-31 11:14*/public class DataStream {/*1.数据流1.1DataInputStream 和 DataOutputStream1.2作用:用于读取或写出基本数据类型的变量或字符串练习:将内存中的字符串、基本数据类型的变量写出到文件中。*/@Testpublic void test() {DataOutputStream dos = null;try {//1.dos = new DataOutputStream(new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\IO\\hello2.txt")));//2.dos.writeUTF("叶文洁");dos.flush();//刷新到文件中dos.writeInt(19);dos.flush();dos.writeBoolean(false);dos.flush();} catch (IOException e) {e.printStackTrace();} finally {try {if(dos != null) {dos.close();}} catch (IOException e) {e.printStackTrace();}}}/*将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!*/@Testpublic void test2(){DataInputStream dis = null;try {//1.dis = new DataInputStream(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\IO\\hello2.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("male:" + isMale);} catch (IOException e) {e.printStackTrace();} finally {//3.try {if(dis != null) {dis.close();}} catch (IOException e) {e.printStackTrace();}}}}
