欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java基础之I/O流详解(1)(3)

来源: javaer 分享于  点击 33479 次 点评:62

RandomAccessFile随机文件读写类):

1)RandomAccessFile类:它直接继承于Object类而非InputStream/OutputStream类,从而可以实现读写文件中任何位置中的数据只需要改变文件的读写位置的指针)。

2)由于RandomAccessFile类实现了DataOutput与DataInput接口,因而利用它可以读写Java中的不同类型的基本类型数据比如采用readLong()方法读取长整数,而利用  readInt()方法可以读出整数值等)。

RandomFileRW.java

  1. import java.io.IOException;   
  2. import java.io.RandomAccessFile;   
  3.    
  4. public class RandomFileRW {   
  5.    
  6.     public static void main(String args[]) {   
  7.         StringBuffer buf = new StringBuffer();   
  8.         char ch;   
  9.            
  10.         try {   
  11.             while ((ch = (char) System.in.read()) != '\n') {   
  12.                 buf.append(ch);   
  13.             }   
  14.                
  15.             // 读写方式可以为"r" or "rw"   
  16.                
  17.             /**  
  18.              * @param mode 1. r 2. rw 3. rws 4. rwd  
  19.              * "r" Open for reading only. Invoking any of the write methods of the resulting object will  
  20.              *      cause an IOException to be thrown.    
  21.              * "rw" Open for reading and writing. If the file does not already exist then an attempt will  
  22.              *      be made to create it.    
  23.              * "rws" Open for reading and writing, as with "rw", and also require that every update to the  
  24.              *      file's content or metadata be written synchronously to the underlying storage device.    
  25.              * "rwd"   Open for reading and writing, as with "rw", and also require that every update to the  
  26.              *      file's content be written synchronously to the underlying storage device.   
  27.              */   
  28.             RandomAccessFile myFileStream = new RandomAccessFile("c:\\UserInput.txt""rw");   
  29.             myFileStream.seek(myFileStream.length());   
  30.             myFileStream.writeBytes(buf.toString());   
  31.                
  32.             // 将用户从键盘输入的内容添加到文件的尾部   
  33.             myFileStream.close();   
  34.         } catch (IOException e) {   
  35.         }   
  36.     }   
  37. }   


相关栏目:

用户点评