【发布时间】:2012-09-29 12:29:07
【问题描述】:
我的意思是,我想从我在 android 上的文本中删除行。我怎样才能删除? 我不想阅读一个 txt 并创建另一个删除行。我想从现有的 txt 中删除行。 谢谢。
【问题讨论】:
-
第一行?最后一行?中线?
标签: java android fileoutputstream android-file
我的意思是,我想从我在 android 上的文本中删除行。我怎样才能删除? 我不想阅读一个 txt 并创建另一个删除行。我想从现有的 txt 中删除行。 谢谢。
【问题讨论】:
标签: java android fileoutputstream android-file
这是一个相当棘手的问题,尽管它看起来微不足道。如果行长度可变,您唯一的选择可能是逐行读取文件以识别目标行的offset 和length。然后从offset 开始复制文件的以下部分,最终将文件长度截断为其原始大小减去目标行的长度。我使用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();
}
}
Here is the full code,包括一个 JUnit 测试用例。使用此解决方案的优点是它应该在内存方面完全可扩展,即由于它使用固定缓冲区,它的内存需求是可预测的,并且不会根据输入文件的大小而改变。
【讨论】:
尝试将文件存储到字符串缓冲区中,替换您要替换的内容,然后完全替换文件的内容。
【讨论】:
您可以通过复制文件中的其余数据来删除一行,然后刷新文件,最后写入复制的数据。Thr 下面的代码搜索要删除的字符串并跳过 stringBuider 中的复制代码。刷新后将stringBuilder的内容复制到同一个文件中
try {
InputStream inputStream = openFileInput(FILENAME);
FileOutputStream fos = openFileOutput("temp", Context.MODE_APPEND);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
String deleteString = "<string you want to del>";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
if (!reciveString.equals(deleteline)) {
stringBuilder.append(receiveString);
}
}
fos.flush();
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(stringBuilder.toString().getBytes());
fos.close();
inputStream.close();
}
【讨论】: