Java_IO之随机访问流与管道流
4902 点击·0 回帖
![]() | ![]() | |
![]() | RandomAccessFile:
特点: 1:该对象即可读取,又可写入。 2:该对象中的定义了一个大型的byte数组,通过定义指针来操作这个数组。 3:可以通过该对象的getFilePointer()获取指针的位置,通过seek()方法设置指针的位置。 4:该对象操作的源和目的必须是文件。 5:其实该对象内部封装了字节读取流和字节写入流。 随机访问原理:就是通过操作索引的方法对指针进行自定义的指定位置来进行读写。 注意:实现随机访问,最好是数据有规律。 此类不是流 class RandomAccessFileDemo{ public static void main(String[] args) throws IOException{ write(); read(); randomWrite(); } //随机写入数据,可以实现已有数据的修改。 public static void randomWrite()throws IOException{ RandomAccessFile raf = new RandomAccessFile("random.txt","rw"); raf.seek(8*4); System.out.println("pos :"+raf.getFilePointer()); raf.write("王武".getBytes()); raf.writeInt(102); raf.close(); } public static void read()throws IOException{ RandomAccessFile raf = new RandomAccessFile("random.txt","r");//只读模式。 //指定指针的位置。 raf.seek(8*1);//实现随机读取文件中的数据。注意:数据最好有规律。 System.out.println("pos1 :"+raf.getFilePointer()); byte[] buf = new byte[4]; raf.read(buf); String name = new String(buf); int age = raf.readInt(); System.out.println(name+"::"+age); System.out.println("pos2 :"+raf.getFilePointer()); raf.close(); } public static void write()throws IOException{ //rw:当这个文件不存在,会创建该文件。当文件已存在,不会创建。所以不会像输出流一样覆盖。 RandomAccessFile raf = new RandomAccessFile("random.txt","rw");//rw读写模式 //往文件中写入人的基本信息,姓名,年龄。 raf.write("张三".getBytes()); raf.writeInt(97); raf.close(); } } 管道流:管道读取流和管道写入流可以像管道一样对接上,管道读取流就可以读取管道写入流写入的数据。 注意:需要加入多线程技术,因为单线程,先执行read,会发生死锁,因为read方法是阻塞式的,没有数据的read方法会让线程等待。 public static void main(String[] args) throws IOException{ PipedInputStream pipin = new PipedInputStream(); PipedOutputStream pipout = new PipedOutputStream(); pipin.connect(pipout); new Thread(new Input(pipin)).start(); new Thread(new Output(pipout)).start(); } 注意:管道必须链接才能用,必须使用多线程来实现 | |
![]() | ![]() |