三种方法
1、读取任意文件的位置
2、追加数据
3、任意位置插入数据
package com.eduask.io.randomAccessFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
/**
* 读取任意文件的位置
*先建一个文件 我的路径是E:\\fileDemo2\\老朋友.txt
* @param path 路径
* @param position 需要读取的位置
* @throws IOException
*/
public static void fun1(String path,int position) throws IOException{
//以只读的方式打开一个RandomAccessFile
RandomAccessFile raf=new RandomAccessFile(path, "r");
//获取RandomAccessFile对象文件指针的位置,初始位置是0
System.out.println("RandomAccessFile文件指针的初始位置:"+raf.getFilePointer());
raf.seek(position);//移动文件指针位置
byte[] buff=new byte[1024];
//用于保存实际读取的字节数
int hasRead=0;
//循环读取
while((hasRead=raf.read(buff))>0){
//打印读取的内容,并将字节转为字符串输入
System.out.println(new String(buff,0,hasRead));
}
}
/**
* 追加数据
* @param args
*
*/
public static void randomWrite(String path){
try{
/**以读写的方式建立一个RandomAccessFile对象**/
RandomAccessFile raf=new RandomAccessFile(path, "rw");
//将记录指针移动到文件最后
raf.seek(raf.length());
// String s="woshi zuijkia de";
// byte bp[]=s.getBytes();
raf.write("我是追加的".getBytes());
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 任意位置插入数据
* @param fileName 文件名
* @param points 数据插入的位置
* @param insertContent 插入的内容
*/
public static void insert(String fileName,long points,String insertContent){
try{
File tmp=File.createTempFile("tmp", null);
tmp.deleteOnExit();//在JVM退出时删除
RandomAccessFile raf=new RandomAccessFile(fileName, "rw");
//创建一个临时文件夹来保存插入点后的数据
FileOutputStream tmpOut=new FileOutputStream(tmp);
FileInputStream tmpIn=new FileInputStream(tmp);
raf.seek(points);
/**将插入点后的内容读入临时文件夹**/
byte [] buff=new byte[1024];
//用于保存临时读取的字节数
int hasRead=0;
//循环读取插入点后的内容
while((hasRead=raf.read(buff))>0){
// 将读取的数据写入临时文件中
tmpOut.write(buff, 0, hasRead);
}
//插入需要指定添加的数据
raf.seek(points);//返回原来的插入处
//追加需要追加的内容
raf.write(insertContent.getBytes());
//最后追加临时文件中的内容
while((hasRead=tmpIn.read(buff))>0){
raf.write(buff,0,hasRead);
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
// try {
// fun1("E:\\fileDemo2\\老朋友.txt",0);
// fun1("E:\\fileDemo2\\老朋友.txt",5);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
randomWrite("E:\\fileDemo2\\老朋友.txt");
insert("E:\\fileDemo2\\老朋友.txt",5,"学个狗屁");
}
}