1、数据流基本使用
package demo02; import org.junit.Test; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * @description: demo11 * @author: liuyang * @create: 2021-09-07 9:31 */ public class Demo11 { /** * 数据流: * 将字符串或者基本数据类型的数据写到文件中, * 再从文件中读取出来 */ @Test public void test1() { DataOutputStream dataOutputStream = null; DataInputStream dataInputStream = null; try { // 数据输出流 dataOutputStream = new DataOutputStream(new FileOutputStream("data.txt")); // 数据输入流 dataInputStream = new DataInputStream(new FileInputStream("data.txt")); // 写字符串 dataOutputStream.writeUTF("刘阳"); dataOutputStream.writeUTF("男"); // 写整数 dataOutputStream.writeInt(20); // 写布尔型 dataOutputStream.writeBoolean(true); // 开始读取,必须按照写的顺序读取 String name = dataInputStream.readUTF(); String gender = dataInputStream.readUTF(); int age = dataInputStream.readInt(); boolean boo = dataInputStream.readBoolean(); System.out.println("name---" + name); System.out.println("gender---" + gender); System.out.println("age---" + age); System.out.println("boo---" + boo); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (dataOutputStream != null) { dataOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (dataInputStream != null) { dataInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }