1.数据流
package sun;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try {
DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("D:\\data.temp"));
try {
dataOutputStream.writeDouble(9.9);
dataOutputStream.writeUTF("Tom");
dataOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
DataInputStream dataInputStream = new DataInputStream(new FileInputStream("D:\\data.temp"));
try {
double p =dataInputStream.readDouble();
System.out.println(p);
System.out.println(dataInputStream.readUTF());
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
运行结果
写入数据流,和读出数据流是对应的,先写入的数据,先读出来,这俩个
System.out.println(p);
System.out.println(dataInputStream.readUTF());
是依次将写入数据读出来。
也可以在读出数据的时候用while循环
package sun;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try {
DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("D:\\data.temp"));
try {
dataOutputStream.writeDouble(9.9);
dataOutputStream.writeDouble(1.1);
dataOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
DataInputStream dataInputStream = new DataInputStream(new FileInputStream("D:\\data.temp"));
try {
while(true) {
double p =dataInputStream.readDouble();
System.out.println(p);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
运行结果
只能在运行结果的时候报错,表示文件读完了。
读取数据的时候也有很多弊端。例如第一个是Double第二是String类型,按照上面循环的方式读出数据,则第二个数据无法读出。
package sun;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try {
DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("D:\\data.temp"));
try {
dataOutputStream.writeDouble(9.9);
dataOutputStream.writeUTF("Tom");
dataOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
DataInputStream dataInputStream = new DataInputStream(new FileInputStream("D:\\data.temp"));
try {
while(true) {
double p =dataInputStream.readDouble();
System.out.println(p);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
运行结果