Ers*_*har 2 java android fileoutputstream android-file
我的意思是,我想从android上的文本中删除一行.我怎么删除?我不想读取一个txt并使用删除行创建另一个.我想删除现有txt中的行.谢谢.
这是一个非常棘手的问题,尽管看起来很简单.在可变行长度的情况下,您可能唯一的选择是逐行读取文件以识别offset和length目标行.然后复制文件的以下部分offset,最后将文件长度截断为原始大小减去目标行的长度.我使用a RandomAccessFile来访问内部指针,也可以按行读取.
该程序需要两个命令行参数:
args[0] 是文件名args[1] 是目标行号(从1开始:第一行是#1)public class RemoveLine {
public static void main(String[] args) throws IOException {
// Use a random access file
RandomAccessFile file = new RandomAccessFile(args[0], "rw");
int counter = 0, target = Integer.parseInt(args[1]);
long offset = 0, length = 0;
while (file.readLine() != null) {
counter++;
if (counter == target)
break; // Found target line's offset
offset = file.getFilePointer();
}
length = file.getFilePointer() - offset;
if (target > counter) {
file.close();
throw new IOException("No such line!");
}
byte[] buffer = new byte[4096];
int read = -1; // will store byte reads from file.read()
while ((read = file.read(buffer)) > -1){
file.seek(file.getFilePointer() - read - length);
file.write(buffer, 0, read);
file.seek(file.getFilePointer() + length);
}
file.setLength(file.length() - length); //truncate by length
file.close();
}
}
Run Code Online (Sandbox Code Playgroud)
这是完整的代码,包括一个JUnit测试用例.使用此解决方案的优点是它应该在内存方面完全可扩展,即因为它使用固定缓冲区,其内存要求是可预测的,并且不会根据输入文件大小而改变.