RandomAccessFile随机读写文件操作类讲解

本文详细介绍Java中的RandomAccessFile类,该类支持文件的随机读写操作。文章通过具体实例展示了如何使用该类来分段读写文件,并解释了其构造方法、常用操作如seek、read和write等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 指针跳过多少个字节。

实例化此类的时候需要传递File类,告诉程序应该操作的是哪个文件,之后有一个模式,文件的打开模式,常用的两种模式:
r:读模式
w:只写
rw:读写,如果使用此模式,如果此文件不存在,则会自动创建。

代码范例

public class FileAccessI implements Serializable {
    RandomAccessFile oSavedFile;
    private int nPos;

    public FileAccessI() throws IOException {
        this("", 0);
    }

    public FileAccessI(String path, int nPos) throws IOException {
        oSavedFile = new RandomAccessFile(path, "rw");//创建一个随机访问文件类,可读写模式
        this.nPos = nPos;
        oSavedFile.seek(nPos);
    }

    public synchronized int write(byte[] b, int nStart, int nLen) {
        int n = -1;
        try {
            oSavedFile.seek(nStart);
            oSavedFile.write(b);
            n = nLen;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return n;
    }

    //每次读取1024*64字节
    public synchronized Detail getContent(long nStart) {
        Detail detail = new Detail();
        //detail.b = new byte[1024 * 64];
        byte[] bytes = new byte[1024 * 64];
        int len = 0;
        try {
            oSavedFile.seek(nStart);
            if ((len = oSavedFile.read(bytes)) != -1) {
                detail.length = len;
                detail.b = new byte[len];
                System.arraycopy(bytes, 0, detail.b, 0, len);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if (nStart + len == getFileLength()) {
                if (oSavedFile != null) {
                    try {
                        oSavedFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return detail;
    }


    public class Detail {

        public byte[] b;
        public int length;
    }

    //获取文件长度
    public long getFileLength() {
        long length = 0l;
        try {
            length = oSavedFile.length();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return length;
    }
}

在主方法中,分段写入文件到内存
private FileAccessI fileAccessI;
private File file = null;
private int lstart = 0;

 String dirName = "";
 System.out.println("下载时接收到的内容:" + new String(bytes));
 //创建文件路径
 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
       // file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), items.get(position).getName());
       dirName = Environment.getExternalStorageDirectory() + currentpageUrl + "/";
 } else {
       //file = new File(getFilesDir(), items.get(position).getName());
       dirName = getFilesDir() + currentpageUrl + "/";
 }
  File fileDir = new File(dirName);
  if(!fileDir.exists()){
       fileDir.mkdirs();
  }
 String fileName = dirName + items.get(position).getName();
 file = new File(fileName);
 if (!file.exists()) {
 try {
     file.createNewFile();
 } catch (IOException e) {
     e.printStackTrace();
   }
  }
  try {
      //分段保存文件到内存
      System.out.println("写入的文件路径" + file.getAbsolutePath());

      int llen = bytes.length;
      fileAccessI = new FileAccessI(file.getAbsolutePath(), lstart);
      fileAccessI.write(bytes, lstart, llen);
      lstart += llen;
      System.out.println("lstart:" + lstart);
  } catch (IOException e) {
            e.printStackTrace();
 }





在主方法中,分段读取文件,上传
Uri uri = data.getData();
path = getPath(this, uri);
Toast.makeText(this, path, Toast.LENGTH_SHORT).show();
String fileName = getFileNameWithSuffix(path);
String url = currentpageUrl + "/";
try {
    fileAccessI = new FileAccessI(path, 0);
  } catch (IOException e) {
      e.printStackTrace();
  }
 length = (int) fileAccessI.getFileLength();
 int length = (int) new File(path).length();
//调用发送数据接口
 registerCallBack(deviceId, callback_upload);
 sendJsonData(deviceId, JsonUtils.upLoadJson(url, fileName, length, MESSAGE_UPLOAD));
 uploadSelectPopupwindow.dismiss();
}

 try {
     FileAccessI.Detail detail;
     int nRead = 0;
     if (nStart < length) {
     detail = fileAccessI.getContent(nStart);
     nRead = detail.length;
     byte[] buffer = new byte[nRead];
     buffer = detail.b;
     nStart += nRead;
     sendDataPre.sendDanaData(deviceId, buffer);
  } catch (Exception e) {
       e.printStackTrace();
        System.out.println("上传失败");
       myHandler.sendEmptyMessage(MESSAGE_UPLOAD_RESULT);
  }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值