需求:
使用Java在不覆写文本的情况下,指定将输入内容插入到指定行。
思路:
1、获取到写入内容的字节数,比如 Size = b.length()
2、使用Java中的RandomAccessFile类,获取写入的文本地址
3、通过randomAccessFile.seek()找到内容书写的定位
4、将定位以下的内容全部向下移动Size 字节
5、通过randomAccessFile.write(b),将内容添加到文本
代码如下:
import java.io.RandomAccessFile;
import java.util.regex.Pattern;
public class ESTest008 {
public static void main(String[] args) throws Exception {
insertNewWord(20, "\n魔兽世界", "F:/HotWords.php");
insertNewWord(20, "\n地下城勇士", "F:/HotWords.php");
}
private static void insertNewWord(long skip, String str, String fileName) {
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "rw");
if (skip < 0 || skip > randomAccessFile.length()) {
return;
}
byte[] b = str.getBytes();
System.out.println(b.length);
System.out.println(randomAccessFile.length());
randomAccessFile.setLength(randomAccessFile.length() + b.length);
//把后面的内容往后面挪
for (long i = randomAccessFile.length() - 1; i > b.length + skip - 1; i--) {
randomAccessFile.seek(i - b.length);
byte temp = randomAccessFile.readByte();
randomAccessFile.seek(i);
randomAccessFile.writeByte(temp);
}
randomAccessFile.seek(skip);
randomAccessFile.write(b);
randomAccessFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果如下:
<?php
$s = <<<'EOF'
地下城勇士
魔兽世界
王者荣耀
骑乐无穷
阴阳师
EOF;
header("Content-type: text/html; charset=utf-8");
header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT', true, 200);
header('ETag: "5816f349-19"');
echo $s;
?>
如果您喜欢我写的博文,读后觉得收获很大,不妨小额赞助我一下,让我有动力继续写出高质量的博文,感谢您的赞赏!!!