将Java基本数据类型或包装类型写入文件,或从文件读取
DataInputStream、DataOutputStream
1.文件读写,结合字节缓冲流
package test.others;
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.FileOutputStream;
import java.io.IOException;
/**
* 数据类型(基本+String)处理流
* 1、输入流 DataInputStream readXxx()
* 2、输出流 DataOutputStream writeXxx()
* 新增方法不能使用多态
* java.io.EOFException :没有读取到相关的内容
* @author WL20180732
*
*/
public class DataDemo01 {
public static void main(String[] args) throws IOException {
write("E:\\test\\read.txt");
read("E:\\test\\read.txt");
}
public static void read(String destPath) throws IOException {
File src = new File(destPath);
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(src)));
double double1 = dis.readDouble();
long long1 = dis.readLong();
String utf = dis.readUTF();
dis.close();
System.out.println(double1 + "-->" + long1 + "-->" + utf);
}
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();
}
}
2.字节流读取
将数据写入字节数组输出流,输出到其他方法中进行读取
package test.others;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* 数据类型(基本+String)处理流
* 1、输入流 DataInputStream readXxx()
* 2、输出流 DataOutputStream writeXxx()
* 新增方法不能使用多态
* java.io.EOFException :没有读取到相关的内容
* @author WL20180732
*
*/
public class DataDemo02 {
public static void main(String[] args) throws IOException {
byte[] bs = write();
read(bs);
System.out.println(bs.length);
}
public static void read(byte[] src) throws IOException {
DataInputStream is = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(src)));
double num1 = is.readDouble();
long num2 = is.readLong();
String str = is.readUTF();
is.close();
System.out.println(num1+ "-->" + num2 + "-->" + str);
}
public static byte[] write() throws IOException {
byte[] dest = null;
double point = 2.5;
long num = 100L;
String str = "数据类型";
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;
}
}