Java文件与io——字节数组流数据流字符串流

时间:2023-03-09 01:02:14
Java文件与io——字节数组流数据流字符串流

字节数组流

ByteArrayInputStream:包含一个内部缓冲区,该缓冲区包含从流中读取的字节。内部计数器跟踪read方法要提供的下一个字节。关闭ByteArrayInputStream无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何IOException.

ByteArrayOutputStream:此类中实现了一个输出流。其中的数据被写入一个byte数组。缓冲区会随着数据的不断写入而自动增长。可使用toByteArray()和toString()获取数据。关闭ByteArrayOutputStream无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何IOException.

例:

public class ByteArrayStream {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
byteArrayStream();
}
public static void byteArrayStream(){
ByteArrayInputStream bai=new ByteArrayInputStream("哈哈哈".getBytes());
ByteArrayOutputStream bao=new ByteArrayOutputStream();
int i=-1;
while((i=bai.read())!=-1){
bao.write(i);
}
System.out.println(bao.toString());
} }

数据流

DataInputStream:数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本Java数据类型。应用程序可以使用数据输出流写入稍后由数据输入流读取的数据。DataInputStream对于多线程访问不一定是安全的。线程安全是可选的,它由此类方法的使用者负责。

DataOutputStream:数据输出流允许应用程序以适当方式将基本Java数据类型写入输出流中。然后,应用程序可以使用数据输入流将数据读入。

public class DataDemo {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DataOut();
DataIn();
}
public static void DataOut(){
try {
OutputStream out=new FileOutputStream("G:\\bbb.txt");
DataOutputStream dos=new DataOutputStream(out);
dos.writeInt(6);//写入4字节
dos.writeUTF("嘎嘎嘎嘎嘎");
dos.writeLong(1512322);
dos.close();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
public static void DataIn(){
try {
InputStream in=new FileInputStream("G:\\bbb.txt");
DataInputStream dis=new DataInputStream(in);
int a=dis.readInt();
String s=dis.readUTF();
long b=dis.readLong();
System.out.println(a);
System.out.println(s);
System.out.println(b);
dis.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

字符串流

StringReader:其源为一个字符串的字符流。

StringWriter:一个字符流,可以用其回收在字符串缓冲区中的输出来构造字符串。关闭StringWriter无效。此类中的方法在关闭该流后仍可被调用,而不会产生任何IOException.

public static void main(String[] args) {
// TODO Auto-generated method stub
stringStream();
}
public static void stringStream(){
String s="编程简单";
StringReader sr=new StringReader(s);
char[] c=new char[2];
int len=-1;
StringBuffer sb=new StringBuffer();
try {
while((len=sr.read(c))!=-1){
sb.append(c,0,len); }
System.out.println(sb);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}