16.6.6 读写随机访问文件

来源:互联网 发布:雕刻大师软件 编辑:程序博客网 时间:2024/05/21 09:50

RandomAccessFile类用于随机访问文件,  它可以把文件看作是一个大的type数组, 可以进行随机读写, 可以获取和指定文件指针的位置. 下边的示例展示了文件的随机读写

package com.cnsuning.file;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;public class UsingRandomAccessFile {public static void display(String fileName){RandomAccessFile file;try {file = new RandomAccessFile(fileName,"r");for(int i=1;i<=3;i++){System.out.println(i+":"+file.readDouble());}System.out.println(file.readUTF());file.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e){e.printStackTrace();}}public static void main(String[] args) {// TODO Auto-generated method stubString testFile = "D:\\test.txt";try {RandomAccessFile file = new RandomAccessFile(testFile,"rw");for(int i=1;i<=3;i++){file.writeDouble(i*3.14);}file.writeUTF("end");file.close();display(testFile);file = new RandomAccessFile(testFile,"rw");file.seek(8*2);file.writeDouble(0);display(testFile);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e){e.printStackTrace();}}}

特别的, 用seek设置文件指针的时候需要考虑啊到字符的字节大小, 正确的设置写入位置, 比如上边double是8字节, 所以插入时候设置指针为8*2

0 0