java應用randomaccessfile在文件隨意率性地位寫入數據。本站提示廣大學習愛好者:(java應用randomaccessfile在文件隨意率性地位寫入數據)文章只能為提供參考,不一定能成為您想要的結果。以下是java應用randomaccessfile在文件隨意率性地位寫入數據正文
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class InsertContent {
public static void insert(String fileName, long pos, String insertContent) throws IOException{
File file = File.createTempFile("tmp", null);
file.deleteOnExit();
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(file);
raf.seek(pos);
byte[] buff = new byte[64];
int hasRead = 0;
while((hasRead = raf.read(buff)) > 0){
fileOutputStream.write(buff);
}
raf.seek(pos);
raf.write(insertContent.getBytes());
//追加文件拔出點以後的內容
while((hasRead = fileInputStream.read(buff)) > 0){
raf.write(buff, 0, hasRead);
}
raf.close();
fileInputStream.close();
fileOutputStream.close();
}
public static void main(String[] args) throws IOException {
insert("F:\AttendanceActivity.java", 57, "拔出的內容rn");
}
}