/**
* 向指定文件,指定位置插入内容
*/
public static void insertContent(String fileName,
long pos,String insertContent) {
RandomAccessFile raf = null;
FileOutputStream tmpOut = null;
FileInputStream tmpIn = null;
try {
File tmp = File.createTempFile("temp", null);
//在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。
tmp.deleteOnExit();
raf = new RandomAccessFile(
fileName, "rw");
//创建一个临时文件来保存插入点后的数据
tmpOut = new FileOutputStream(tmp);
tmpIn= new FileInputStream(tmp);
raf.seek(pos);
byte[] buf = new byte[64];
//用于保存实际读取的数据
int hasRead = 0;
//使用循环方式读取插入点后的数据
while((hasRead = raf.read( buf)) > 0) {
//将读取的数据写入临时文件
tmpOut.write(buf,0,hasRead);
}
//将指针定位到pos位置
raf.seek(pos);
//追加需要插入的内容
raf.write(insertContent.getBytes());
//追加临时文件中的内容
while((hasRead = tmpIn.read(buf)) > 0) {
raf.write(buf,0,hasRead);
}
} catch (IOException e) {
System.out.println("文件创建失败");
} finally {
try {
raf.close();
tmpIn.close();
tmpOut.close();
} catch (IOException e) {
System.out.println("文件关闭出错");
}
System.out.println("数据插入成功");
}
}
* 向指定文件,指定位置插入内容
*/
public static void insertContent(String fileName,
long pos,String insertContent) {
RandomAccessFile raf = null;
FileOutputStream tmpOut = null;
FileInputStream tmpIn = null;
try {
File tmp = File.createTempFile("temp", null);
//在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。
tmp.deleteOnExit();
raf = new RandomAccessFile(
fileName, "rw");
//创建一个临时文件来保存插入点后的数据
tmpOut = new FileOutputStream(tmp);
tmpIn= new FileInputStream(tmp);
raf.seek(pos);
byte[] buf = new byte[64];
//用于保存实际读取的数据
int hasRead = 0;
//使用循环方式读取插入点后的数据
while((hasRead = raf.read( buf)) > 0) {
//将读取的数据写入临时文件
tmpOut.write(buf,0,hasRead);
}
//将指针定位到pos位置
raf.seek(pos);
//追加需要插入的内容
raf.write(insertContent.getBytes());
//追加临时文件中的内容
while((hasRead = tmpIn.read(buf)) > 0) {
raf.write(buf,0,hasRead);
}
} catch (IOException e) {
System.out.println("文件创建失败");
} finally {
try {
raf.close();
tmpIn.close();
tmpOut.close();
} catch (IOException e) {
System.out.println("文件关闭出错");
}
System.out.println("数据插入成功");
}
}