处理流
输入流:DataInputStream
输出流:DataOutputStream
数据+类型的输入输出
import java.io.*;
/**
* 数据类型(基本+String)处理流
* DataInputStream
* DataOutputStream
* java.io.EOFException 没有读取到相关的内容
*/
public class Demo08 {
public static void main(String[] args) throws IOException {
write("D:/test.txt");
read("D:test.txt");
readByte(writeByte());
}
/**
* 从文件读取数据类型
*/
public static void read(String srcPath) throws IOException {
//创建源
File src=new File(srcPath);
//选择流
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(src)));
//读取
double d=dis.readDouble();
long l=dis.readLong();
String str=dis.readUTF();
System.out.println(str);
dis.close();
}
/**
* 数据+类型输出到文件
* @param destPath
* @throws IOException
*/
public static void write(String destPath) throws IOException {
double point=2.5;
long num=100L;
String str="数据类型";
//创建源
File dest=new File(destPath);
//选择流
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
//写出的顺序为读取准备,保持一致,不按顺序,数据会出错
dos.writeDouble(point);
dos.writeLong(num);
dos.writeUTF(str);
dos.flush();
dos.close();
}
/**
* 数据+类型输出到字节数组
*/
public static byte[] writeByte() throws IOException {
double point=2.5;
long num=100L;
String str="数据类型";
byte[] dest=null;
//选择流
ByteArrayOutputStream bos=new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(bos));
//写出的顺序为读取准备,保持一致,不按顺序,数据会出错
dos.writeDouble(point);
dos.writeLong(num);
dos.writeUTF(str);
dos.flush();
dest=bos.toByteArray();
dos.close();
return dest;
}
/**
* 从字节数组读取数据+类型
*/
public static void readByte(byte[] src) throws IOException {
DataInputStream dis=new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(src)));
//读取
double d=dis.readDouble();
long l=dis.readLong();
String str=dis.readUTF();
System.out.println(d+"-->"+l+"-->"+str);
dis.close();
}
}