管道流 :
PipedinputStream和PipedOutputStream
用于多线程的流
在用管道流之前需要先将两者合二为一
方法可有
pipedInputStream(pipedOutputStream src) 或者pipedInputStream()后使用对象名的
connect(PipedoutputStream src)方法
例子:public class test {
/**
* @param args
* 管道流
*/
public static void main(String[] args) {
try {
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
pis.connect(pos);
reader r = new reader(pis);
writer w = new writer(pos);
new Thread(r).start();
new Thread(w).start();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
class reader implements Runnable{
PipedInputStream pis = new PipedInputStream();
reader(PipedInputStream pis){
this.pis = pis;
}
public void run(){
try {
byte[] bos = new byte[1024];
System.out.println("正在读取中");
int len = pis.read(bos); //此方法是堵塞式方法,在没有得到值前会一直等待值的出现。
System.out.println("已经读取到马上输出");
Thread.sleep(1000);
String s = new String(bos,0,len);
System.out.println(s);
pis.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println("读入失败");
}
}
}
class writer implements Runnable{
PipedOutputStream pos = new PipedOutputStream();
writer(PipedOutputStream pos){
this.pos = pos;
}
public void run()
{
try {
Thread.sleep(3000);
pos.write("outputwrit".getBytes());
pos.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println("输出流失败");
}
}
}
RandomAccessFile
该类不算是IO体系中的子类,
而是直接结成自Object,但是它是IO包中的成员,因为它具备读和写的功能。
内部封装了一个数组,而且通过指针对数组的元素进行操作。
可以通过getFilePointer获取指针位置
同时可以通过seek改变指针的位置
RandomAccessFile构造函数中需要两个参数,一个为文件存放位置和格式,另一个则为权限
"rw"(可读可写),"r"(只读)
RandomAccessFile方法有writer();但是只是写入
其实完成读写的原理就是内部封装了字节流输入和输出流
通过构造函数可以看出,该类只能操作文件。而且操作文件还有模式:
public static void writerFile()
{
RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
//调整对象中指针.
//raf.seek(int);调整指针位置
//跳过指定字节数
raf.skipBytes(int);
}
DataInputStream与DataOutputStream
可以用于操作基本数据类型
例子:
ByteArrayStream 用于操作字节数组的流对象。
ByteArrayStream:在构造的时候,需要接受数据源,而且数据源是一个字节数组。
ByteArrayStream:在构造的时候,不用定义数据目的,因为该对象中已经内部封装了可变长度的字节数组。这就是数据目的地。
因为这两个流对象都操作的数组,并没有使用系统资源,所以不用进行close关闭
在流操作规律讲解时:
源设备,
键盘 System.in,硬盘 FileSteam,内存 ArrayStream。
目的设备:
控制台 System.out,硬盘 FileSteam,内存 ArrayStream。
例子:
public static void main(String[] arg)
{
//数据源
ByteArrayInputstream bis = new ByteArrayInputStream("abcdef".getByte());
//数据目的
ByteArrayOutputStream bos - new ByteArrayOutputstream();
int by = 0
while((by=bis.read())!=-1)//用流的读写思想来操作数据
{
bos.write(by);
}
system.out.println(bos.size())
}
编码:字符串编程字节数组
解码:字节数组编程字符串