您的位置:首页 > 其它

利用RandomAccessFile类在指定文件指定位置插入内容

2015-09-06 17:53 405 查看
package File;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

/*利用RandomAccessFile类在指定文件指定位置插入内容。*/

public class InsertContent {
public static void insert(String fileName, long pos, String insertContent)
throws IOException {
File tmp = File.createTempFile("tmp", null);
tmp.deleteOnExit();
try (RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
FileOutputStream tmpOut = new FileOutputStream(tmp);
FileInputStream 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);
}

raf.seek(pos);
raf.write(insertContent.getBytes());
while((hasRead = tmpIn.read(buf))>0)
{
raf.write(buf,0,hasRead);
}
}
}

public static void main(String[] args) throws IOException
{
insert("./src/File/InsertContent.java",45,"插入内容!\n");

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: