【发布时间】:2012-11-16 12:07:24
【问题描述】:
我尝试在 txt 文件中搜索一个字符串并在其上方插入一些特定内容。
遗憾的是,输出看起来与我的预期完全不同。
有人可以给我一个提示吗?
这就是我有多远!
String description= "filename.txt";
String comparison=" return model;";
RandomAccessFile output = null;
try
{
output = new RandomAccessFile(description, "rw" );
String line = null;
while ((line = output.readLine()) != null) {
if (line.equals(comparison)){
//System.out.println("alt: "+line);
output.seek(output.getFilePointer()-line.getBytes().length);
output.writeChars("new stuff; \n");
//System.out.println("new: "+output.readLine());
}
}
}
catch ( IOException e ) {
e.printStackTrace();
}
finally {
if ( output != null ){ try { output.close(); } catch ( IOException e ) { e.printStackTrace(); }}
}
这是我尝试阅读的文件:
/*filename.txt*/
some longer content ~ 100kB
return model;
further content
这就是我希望得到的
/*filename.txt*/
some longer content ~ 100kB
new stuff;
return model;
further content
【问题讨论】:
-
而你实际上得到了什么?
-
这就是你所拥有的,这就是你期望得到的......但是你得到了什么?
-
使用两个文件。复制到您想要的行到新文件中。添加你的新行。然后再次将其余行复制到文件中。最后,将新文件的全部内容复制到旧文件中。
-
由于编码问题,我得到了一些我无法在此处复制和粘贴的内容。此外,似乎 writeChars 命令执行了错误的值并且不插入它们。
标签: java seek randomaccessfile