IO流总结5

管道流 :
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())
}

 

 

编码:字符串编程字节数组
解码:字节数组编程字符串

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值