基本数据类型+String 保留数据+类型(供机器解析阅读)
输入流:DataInputStream readXxx()
输出流:DataOutputStream writeXxx()
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 数据类型(基本+String)处理流
* 数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java数据类型。
* 应用程序可以使用数据输出流写入稍后由数据输入流读取的数据。
* DataInputStream 对于多线程访问不一定是安全的。 线程安全是可选的,它由此类方法的使用者负责。
* 1、输入流DataInputStream readXxx()
* 2、输出流DataOutputStream writeXxx()
* 使用新增方法不能使用多态
* java.io.EOFException:已达到文件的末尾,没有读取到相关的内容
* @author Administrator
*
*/
public class DateDemo {
public static void main(String[] args) {
try {
// write("D:/安装包/aa/bb/dd/a.txt");
read("D:/安装包/aa/bb/dd/a.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从文件中读取数据+类型
* @throws IOException
*/
public static void read(String destPath) throws IOException{
//创建源
File src = new File(destPath);
//选择流
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(src)));
double point = dis.readDouble();
long num = dis.readLong();
String str = dis.readUTF();
dis.close();
System.out.println(point + "," + num + "," + str);
}
/**
* 数据+类型同时输出到文件,因为正常情况下,都是把数据已字节的形式传输,并没有类型一说
* @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();
}
}
/**
* 数据+类型输出到字节数组中
* @throws IOException
*/
public static byte[] write() throws IOException{
//目标数组
byte[] des = null;
double point = 2.5;
long num = 100L;
String str = "数据类型";
//选择流 DataOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(baos)
);
//操作 写出的顺序与读取的顺序必须一致 为读取准备
dos.writeDouble(point);
dos.writeLong(num);
dos.writeUTF(str);//字符串
dos.flush();
des = baos.toByteArray();
baos.close();
dos.close();
return des;
}
/**
* 从字节数组读取数据(基本+String)+类型
* @throws IOException
*/
public static void read(byte[] src) throws IOException{
//选择流
DataInputStream dis = new DataInputStream(
new BufferedInputStream(new ByteArrayInputStream(src))
);
//操作 读取的顺序与写出一致且必须存在才能读取
//顺序不一致,数据存在问题
double point = dis.readDouble();
long num = dis.readLong();
String str = dis.readUTF();
dis.close();
System.out.println(point + "," + num + "," + str);//内容:2.5,100,数据类型
}
}