欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java核心编程之文件随机读写类RandomAccessFile详解

程序员文章站 2024-03-31 11:08:34
本文实例为大家分享了android九宫格图片展示的具体代码,供大家参考,具体内容如下 1.randomaccessfile   randomaccessfile主要用于...

本文实例为大家分享了android九宫格图片展示的具体代码,供大家参考,具体内容如下

1.randomaccessfile

  randomaccessfile主要用于文件内容的读写访问

2.访问模式

  “r”:只读方式。

  “rw”:打开以便读取和访问,如果文件不存在则创建文件。

  “rws”: 除了‘rw‘功能以外,文件内容或者元数据更新时一同写入。

  “rwd”:除了‘rw‘功能以外,文件内容更新时一同写入。

3.使用案例

package test;

import java.io.file;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.io.randomaccessfile;

public class randomaccess {
 
 
 public static void main(string[] args) {
  try {
   file file = new file("c:\\img\\666.txt");
   
   //打开文件
   randomaccessfile randomaccess = new randomaccessfile(file,"rwd"); //访问文件 
   long lenth = randomaccess.length(); //获取文件长度
   system.out.println("lenth:"+lenth);
   randomaccess.seek(4); //设置指针位置
   
   //读取文件
   int c = randomaccess.read(); //读取一个字节
   system.out.println("c:"+c);
   system.out.println("c:"+(char)c); //转换为字符
   
   byte[] b = new byte[3]; //读取字节数字,创建数组
   randomaccess.read(b, 1, 2); //从指针1处读取两个字节写入数组b中
   string s = new string(b); //转换为字符串
   system.out.println("byte:"+s); //输出
   
   //写入文件
   file file2 = new file("c:\\img\\777.txt");
   if(!file2.getparentfile().exists()){
    file2.getparentfile().mkdirs();
   } 
   file2.createnewfile();
   randomaccessfile randomaccess2 = new randomaccessfile(file2,"rwd"); //访问文件 
   randomaccess2.write(b); //写入字符数组
   
   //关闭文件
   randomaccess.close();
   randomaccess2.close();
   
  } catch (filenotfoundexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  } catch (ioexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
  
  
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。