RandomAcessFile的使用
构造函数
RandomAccessFile(File file, String mode);
创建从中读取和向其中写入的随机访问文件流,该文件由File参数指定
RandomAccessFile(String name, String mode);
创建从中读取和向其中写入的随机访问文件流,该文件具有指定的名称
其中:
mode:4种模式
- “r”: 以只读的方式打开 调用write方法会抛出IOException
2)“rw”: 便于读取和写入
3)“rws”: 便于读取和写入,同时对文件的内容和元数据的更新都会同步存储到基础存储设备
4)“rwd”: 便于读取和写入,同时对文件的内容的更新都会同步存储到基础存储设备
常用的方法
public void seek(long pos)
设置文件指针的位置
public native long getFilePointer()
返回文件指针的位置
public int read();
从此文件中读取一个数据字节(8bit)
public int write(int b);
向此文件中写入一个数据字节(8bit)
具体操作
随机访问文件当中的某一部分数据,打印出来500之后的数据
public static void main(String[] args) {
//随机访问文件当中的某一部分数据
RandomAccessFile raf = null;
{
try {
raf = new RandomAccessFile("a.txt", "r");
//将文件指针移动到指定位置
raf.seek(500);
byte[] buf = new byte[256];
int hasRead = 0;//真实读取到的字节数 <= buf.length
while((hasRead=raf.read(buf)) > 0){
System.out.println(new String(buf, 0, hasRead));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在指定位置追加"西安图论软件科技有限公司"
public static void main(String[] args) {
RandomAccessFile raf = null;
FileOutputStream fos = null;
FileInputStream fis = null;
try {
raf = new RandomAccessFile("a.txt","rws");
raf.seek(256);
File file = new File("./b.txt");
if(!file.exists()){
file.createNewFile();
}
fis = new FileInputStream(file);
fos = new FileOutputStream(file);
byte[] bytes = new byte[256];
int len;
while((len = raf.read(bytes))>0){
fos.write(bytes,0,len);
}
raf.seek(256);
String ss = "图论有限科技公司";
raf.write(ss.getBytes());
while((len = fis.read(bytes))!=-1){
raf.write(bytes,0,len);
}
fis.close();
fos.close();
if(file.exists()){
file.delete(); }
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}