(1) 创建随机访问文件
- RandomAccessFilede构造方法如下:
- 用文件名 public RandomAccessFile(String name,String mode);
- 用文件对象 public RandomAccessFile(File file,String mode);
其中,mode参数决定了访问文件的权限,如只读’r’或读写’wr’等。
(2) 定位及读写访问
- 在文件里移动指针:
- long getFilePointer(); 返回当前指针
- void seek(long pos); 将文件指针定位到一个绝对地址。地址是相对于文件头的偏移量。地址0表示文件的开头。
- long length(); 返回文件的长度。
- skipBytes(long i):从前往后拨弄指针的位置,就是跳过多少个字节读取数据。
- 可以使用在DataInputStream 和DataOutputStream里出现的所有read()和write()方法。
```java
import java.io.*;
class count{
public static void main(String args[])
{
} }long count; //用来表示访问计数值try {RandomAccessFile fio = null;fio = new RandomAccessFile("log.txt", "rw");if (fio.length()==0) //新建文件夹的长度为0count=1L; //长整型,第一次访问else{fio.seek(0); //定位到文件首字节count = fio.readLong(); //读原来的计数值count=count+1L; //计数+1}fio.seek(0);fio.writeLong(count); //写入新的计数值fio.close();} catch (FileNotFoundException e) {e.printStackTrace();}catch(IOException e){e.printStackTrace();};
```javaBufferedReader in=new BufferedReader(new InputStreamReader(System.in))};String s=in.readLine();RandomAccessFile myFile=new RandomAccessFile(“java.log”,”rw”);myFile.seek(myFile.length()); //将指针定到文件尾myFile.writeBytes(s+”\n”); //写入数据myFile.close();
int data_arr[] = {12, 32, 43, 45, 1, 5};try{RandomAccessFile randf=new RandomAccessFile("temp.dat","rw");for(int i = 0; i < data_arr.length; i++){randf.writeInt(data_arr[i]);}for(int i = data_arr.length-1 ; i >= 0; i--){randf.seek(i * 4L); //int 数据占4个字节System.out.println(randf.readInt());}randf.close();}catch(IOException e){System.out.println("File access error" + e);}
