我想从文本文件中删除一个字符串。我已经看到我需要一个临时文件来执行此操作。我想从list.txt文件中读取并删除其中的字符串。我想要搜索的文件已经创建并填充了我已经看过其他帖子,我正在尝试将其修改为我自己的个人项目。目前我有:
package com.nullwall.listmanager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
public class IPR3Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DoWork("TestString");
}
public void DoWork(String deleteFromFile)
{
try{
String delete = deleteFromFile;
String line;
//locates a new file named list.txt
File root = new File(Environment.getExternalStorageDirectory(),"projects");
File file = new File(root, "list.txt");
//creates buffers
BufferedReader bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));
StringBuffer stringBuffer = new StringBuffer();
//Loads list.txt into bufferedReader, deletes line and moves on
while ((line = bufferedReader.readLine()) != null)
{
if (line.equals(deleteFromFile))
{
line.replace(deleteFromFile, "");
stringBuffer.append("\n");
}
else
{
stringBuffer.append(line);
stringBuffer.append("\n");
}
}
//Entire file has now been loaded into memory
//creates new Filewriter, append to false, rewrites list.txt with stringBuffer minus string
FileWriter writer = new FileWriter(file, false);
writer.write(stringBuffer.toString());
System.out.println("file written");
//closes writer
writer.flush();
writer.close();
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
我的list.txt包含如下随机字符串:
notstring
notstring
notstring
teststring
notstring
notstring
跑步后,没有任何反应。我很喜欢这样做File IO所以请不要忽略我可能错过的简单事情。谢谢!
答案 0 :(得分:0)
尝试将文件存储到String缓冲区中替换您要替换的内容,然后完全替换该文件的内容。另外一件事是File IO在android中不一定相同。由于android使用上下文,因此文件IO的方法是不同的。检查开发站点以获取有关来自android的文件IO的更多信息。