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

来源:互联网 发布:xp 数据执行保护 编辑:程序博客网 时间:2024/05/22 07:58

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;}@Overridepublic 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;}@Overridepublic void run() {// TODO Auto-generated method stubtry{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 exceptionthrow 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 stubRandomAccessFile 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
原创粉丝点击