首页 > 技术文章 > 逆序读取文本文件内容

yilunzhang 2018-02-07 14:29 原文

RandomAccessFile类的主要功能是完成随机读取功能,可以读取指定位置的内容。
之前的File类只是针对文件本身进行操作的,而如果要想对文件内容进行操作,则可以使用RandomAccessFile类,此类属于随机读取类,可以随机读取一个文件中指定位置的数据。
RandomAccessFile类的常用的操作方法
1、public  RandomAccessFile(File file, String mode)throws FileNotFoundException  构造方法  接收File类的对象,指定操作路径,但是在设置时需要设置模式:"r": 只读、"w": 只写、"rw": 读写。
2、public RandomAccessFile(String name, String mode) throws FileNotFoundException 构造方法 不再使用File类对象表示文件,而是直接输入了一个固定的文件路径。
3、public void close() throws IOException   关闭操作
4、public int read(byte[] b) throws IOException 将内容读取到一个byte数组之中
5、public final byte readByte()  throws IOException 读取一个字节
6、public final int readInt()  throws IOException从文件中读取整型数据。
7、public void seek(long pos) throws IOException 设置读指针的位置。
8、public final void writeBytes(String s) throws IOException 将一个字符串写入到文件之中,按字节的方式处理。
9、public final void writeInt(int v) throws IOException 将一个int型数据写入文件,长度为4位。
10、public int skipBytes(int n) throws IOException 指针跳过多少个字节。
 
实现倒序读取文本文件:
 
public static String getLine() {  
    RandomAccessFile rf = null;  
    try {  
      rf = new RandomAccessFile("D:\\file.txt", "r");  
      long len = rf.length();   //文件长度  
      long nextend =  len - 1;  //指针是从0到length-1  
      String line = null;  
      rf.seek(nextend); //seek到最后一个字符  
      int c = -1;  
      while (nextend >= 0) {  
        c = rf.read();  
        if (c == '\n' || c=='\r') //只有行与行之间才有\r\n,这表示读到每一行上一行的末尾的\n,而执行完read后, 指针指到了这一行的开头 
        {  
          line =  new String(rf.readLine().getBytes("ISO-8859-1"), "utf8");  
          System.out.println(line);  
        }  
   
        if (nextend == 0) { // 当文件指针退至文件开始处,输出第一行  
            rf.seek(0); //read()方法指针从0到了1,需重置为0  
          System.out.println(new String(rf.readLine().getBytes("ISO-8859-1"), "utf8"));  
        }  
        else   
        {  
             rf.seek(nextend-1);//为下一次循环做准备  
        }  
              
        nextend--;  
          
      }  
    } catch (FileNotFoundException e) {  
      e.printStackTrace();  
    } catch (IOException e) {  
      e.printStackTrace();  
    } finally {  
      try {  
        if (rf != null)  
          rf.close();  
      } catch (IOException e) {  
        e.printStackTrace();  
      }  
    }  
  }  

  

 

推荐阅读