使用RandomAccessFile类可以对文件进行自由灵活的操作。
自定义封装两个方法实现对文件内容操作。
import java.io.*;
import java.util.*;
public class FileHandler {
private StringBuffer tempstring = new StringBuffer("");
//读取文件内容
public long readFileContent(RandomAccessFile file, long pointer) throws IOException{
long readtotallen = 0;
try{
// 定位指针
file.seek(pointer);
//缓存区
var buffer = new byte[1024];
int readnum = 0;
//循环读取
while ((readnum = file.read(buffer)) > 0){
String readtext = new String(buffer,0,readnum);
this.tempstring.append(readtext);
//System.out.println("读取文件内容" + readtext + "文件指针" + file.getFilePointer());
readtotallen += readnum;
}
}
catch(IOException e){
e.printStackTrace();
}
return readtotallen;
}
public boolean writeFileContent(RandomAccessFile file, long pointer, FileHandler.WriteFileModule isappend, String content) throws IOException{
boolean writefile = true;
try{
// 处理写文件内容
byte[] contentbyte = content.getBytes();
//指定位置读取文件内容缓存,插入文件模式用
this.readFileContent(file,pointer);
// 追加/插入内容
if (isappend.compareTo(FileHandler.WriteFileModule.APPEND) == 0 || isappend.compareTo(FileHandler.WriteFileModule.INSERT) == 0){
file.seek(pointer);
file.write(contentbyte);
file.write(this.tempstring.toString().getBytes());
}
// 覆盖文件内容
if (isappend.compareTo(FileHandler.WriteFileModule.COVER) == 0){
file.setLength(pointer); //清空指定位置后的内容
file.write(contentbyte);
}
}
catch (IOException e){
e.printStackTrace();
writefile = false;
}
return writefile;
}
public static void main(String[] args) throws IOException{
try (
Scanner scan = new Scanner(System.in);
var file = new RandomAccessFile("test.txt","rw"); //以rw模式打开文件
){
var filehandler = new FileHandler();
var curpointerposition = file.length();
scan.useDelimiter("\n");
while(scan.hasNext()){ //从键盘循环输入并写入文件
String content = scan.next();
if (content.indexOf("exit") > -1) break; //键盘输入exit结束
//写文件内容
var iswritefile = filehandler.writeFileContent(file,curpointerposition,FileHandler.WriteFileModule.APPEND,content);
if (iswritefile){
curpointerposition = file.getFilePointer(); //获取文件当前指针位置
}else{
System.out.println("写文件报错!");
//throws IOException("111");
break;
}
}
System.out.println("文件大小:" + file.length());
}
catch (IOException e){
e.printStackTrace();
}
}
//写文件模式内部枚举类 APPEND 追加,COVER 覆盖,INSERT 插入
public static enum WriteFileModule{
APPEND, COVER, INSERT;
}
}