DataInputStream :数据输入流允许程序以与机器无关方式从底层输入流中读取基本JAVA数据类型,DAtaInputStream对于多线程是不安全的
DataOutPutStream :数据输出流允许应用程序以适当的方式将基本java数据类型写入输入流中
如下使用数据流进行文件的读写:
public class DataStreamDemo {
public static void Reader (){
try {
InputStream in = new FileInputStream("G://3.txt");
// 根据字节输入流构造一个字节输入流
DataInputStream dis = new DataInputStream(in);
int flag = dis.readInt();
String info = dis.readUTF();
System.out.println("info=" +info +"flag=" +flag);
dis.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void Write(){
try {
OutputStream os = new FileOutputStream("G://3.txt");
// 根据字节输出流构造一个数据输出流
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(1);
dos.writeUTF("床前明月光,疑是地上霜");
dos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Write();
Reader ();
}
}
StringReader &&StringWriter
StringReader其源于一个字符串的字符流继承自Reader
StringWrite 继承自Writer
一个字符流,可以用其回收在字符串缓冲区中的输出来构造字符串。关闭SringWriter无效,此类中的方法在关闭流后仍可被调用,而不会产生IO异常。
实例如下:
public static void Writer(){
//StringWriter 使用StringBuffer实现底层通过字节数组实现
StringWriter sw = new StringWriter();
sw.write("窗前明月光,疑是地上霜");// 数据存储在StringBuffer中
// 读取操作,根据字符创构造一个字符串输入流
StringReader sr = new StringReader(sw.toString());
char[] cs = new char [11];
int len =-1;
try {
while ((len=sr.read(cs))!=-1){
System.out.println(new String (cs,0 ,len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
ByteArrayOutPutStream && ByteArrayInputStream
ByteArrayOutPutStream 实现一个输出流,其中的数据被写入一个byte数组,缓冲区会随着数据的不断写入而自动增长,初始化为32个字节。
关闭ByteArrayOutPutStream无效,此类中的方法在关闭流后仍可被调用 (该类中的close方法只定义而没有实现),而不会产生IO异常。
ByteArrayInputStream 类包含一个内部缓冲区,该缓冲区包含从流中读取的字节,内部计数器跟踪read方法要提供的下一个字节。使用该类的时候需要定义一个字节数组。
实例如下:
public static void ByteArrayWriter (){
ByteArrayOutputStream baos = new ByteArrayOutputStream();// 默认字节数组打大小为32
String info = "水不在深,有龙则灵";
try {
baos.write(info.getBytes());//将数据写入缓冲区
baos.write(10);
// baos.toByteArray();//将数据转换为字节数组
baos.close();//关闭无效
} catch (IOException e) {
e.printStackTrace();
}
// 根据字节数组,构造一个字节数组输入流
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
byte [] bytes = new byte [1024];
int len =-1;
StringBuilder sb = new StringBuilder();
try {
while ((len=bais.read(bytes))!=-1){
sb.append(new String (bytes, 0 ,len));
}
bais.close();
System.out.println(sb);
} catch (IOException e) {
e.printStackTrace();
}
}