java基础之IO流中的PipedStream管道流和RandomAcessFile

1、PipedStream管道流

package com.j2se.io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 学习管道流
 * @author Administrator
 *
 */
public class PipedStreamDemo {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		PipedInputStream pis=new PipedInputStream();
		PipedOutputStream pos=new PipedOutputStream();
		pis.connect(pos);//管道输入流和管道输出流对接
		new Thread(new WritePiped(pos)).start();
		new Thread(new ReadPiped(pis)).start();
	}
  
}
class WritePiped implements Runnable{

	private PipedOutputStream pos=null; 
	public  WritePiped(PipedOutputStream pos) {
		this.pos=pos;
	}
	@Override
	public void run() {
		 try{
			 pos.write("Hello PipedOutStream le !!".getBytes());
			 pos.close();
		 }catch (Exception e) {
			// TODO: handle exception
			 throw new RuntimeException("输出管道流出错");
		}
	}
  }
  class ReadPiped implements Runnable{
	  private PipedInputStream pis=null;
	  public ReadPiped(PipedInputStream pis){
		  this.pis=pis;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try{
			byte[] buffer=new byte[1024];
			int len= pis.read(buffer);
			String result=new String(buffer, 0, len);
			System.out.println("result="+result);
			pis.close();
		}catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException("读取管道流出错。。。");
		}
	}
	  
  }

2、RandomAcessFile:

package com.j2se.io;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 该类不是IO体系中的子类
 * 而是直接继承自object
 * RandomAccessFile包装了io流的读写操作,根据指定的模式进行读写
 * 内部封装了一个数组,而且通过指针对数组的元素进行操作
 * 可以通过getFilePointer获取指针位置
 * 如果模式为r,侧不会创建文件,会去读取一个已存在的文件
 * 
 * @author Administrator
 *
 */
public class RandomAcessFileDemo {

	/**
	 * 随机访问文件类的学习
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		//write_1();
		read_1();
	}

	public static void read_1() throws IOException {
		// TODO Auto-generated method stub
		RandomAccessFile raf=new RandomAccessFile("src/raf.txt", "r");
		byte buffer[]=new byte[4];
		raf.read(buffer);
		String s=new String(buffer);
		int age=raf.readInt();
		System.out.println("name:"+s);
		System.out.println("age:"+age);
		raf.close();
	}

	public static void write_1() throws IOException{
		RandomAccessFile raf=new RandomAccessFile("src/raf.txt", "rw");
		raf.write("李四".getBytes());
		raf.writeInt(18);
		raf.close();
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值