1、数据流特性
1)属于处理流。因此 使用必须套接在字节流上。
2)专门用来处理八种数据类型和字符串。为此提供了专门的方法:
void writeByte(byte) void readByte();
void writeInt(int) void readInt();
3)在处理八种基本数据类型时可以保证数据类型不改变
4)适合在网络中传输基本数据类型。
2、案例:将基本数据类型存盘到指定的路径中。从路径中读取基本数据类型 还有一部分异常处理。
代码:
public class DataInputOutputStream {
public static void main(String[] args) {
String path1 = "e:/hahha.txt";
FileInputStream fis = null;
FileOutputStream fos = null;
DataInputStream dis = null;
DataOutputStream dos = null;
byte b1 = 123;
int i1 = 3435;
short s1 = 1234;
String str = "张鑫铭";
try {
fos = new FileOutputStream(path1);
fis = new FileInputStream(path1);
dos = new DataOutputStream(fos);
dos.writeByte(b1);
dos.writeInt(i1);
dos.writeShort(s1);
dos.writeUTF(str);
//刷新
dos.flush();
dis = new DataInputStream(fis);
b1 = dis.readByte();
s1 = dis.readShort();
i1 = dis.readInt();
str = dis.readUTF();
System.out.println(b1);
System.out.println(s1);
System.out.println(i1);
System.out.println(str);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if( dos != null ){
try {
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dis != null ){
try {
dis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
int re = add(Integer.MAX_VALUE,2);
System.out.println("!!!!!!!:"+re);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("超出Integer最大数范围");
}
}
public static int add(int a,int b) throws Exception{
int c = a+b;
if(c>Integer.MAX_VALUE||c<Integer.MAX_VALUE){
throw new Exception();
}
else{
return c;
}
}
}