其他流---基本数据处理流

时间:2022-07-22
本文章向大家介绍其他流---基本数据处理流,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

!!!写入顺序不可与读取顺序相反!!!

基本数据处理流<====>文件

与字符流基本相同

完整代码

package cn.hxh.io.other;

import java.io.*;

public class DataDemo01 {
	

	public static void main(String[] args) throws IOException {
		write("D:/aa/a.txt");
		read("D:/aa/a.txt");
	}
	public static void read(String destPath) throws IOException {
		File dest = new File(destPath);
		DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(dest)));
		
		int i = dis.readInt();
		long l = dis.readLong();
		String s = dis.readUTF();
		System.out.println(i + " " + l + " " + s);
		dis.close();
	}
	public static void write(String destPath) throws IOException {
		int i = 1;
		long l = 100;
		String s = "字符流写入测试";
		
		File dest = new File(destPath);
		DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
		dos.writeInt(i);
		dos.writeLong(l);
		dos.writeUTF(s);
		dos.flush();
		dos.close();
	}

}

基本数据处理流<====>字节数组 (重点)

与字符流基本相同

完整代码

package cn.hxh.io.other;

import java.io.*;

public class DataDemo02 {
	public static void main(String[] args) throws IOException {
		read(write());
	}
	
	public static void read(byte src[]) throws IOException {
		DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(src)));
		
		int i = dis.readInt();
		long l = dis.readLong();
		String s = dis.readUTF();
		
		System.out.println(i + " " + l + " " + s);
		dis.close();
	}
	
	public static byte[] write() throws IOException {
		int i = 1;
		long l = 100;
		String s = "字符流写入测试";
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(bos));
		dos.writeInt(i);
		dos.writeLong(l);
		dos.writeUTF(s);

		dos.flush();
		dos.close();
		return bos.toByteArray();
	}

}