我需要从txt文件中删除行
FileReader fr= new FileReader("Name3.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
br.close();
我不知道代码的继续。
答案 0 :(得分:0)
您可以阅读所有行并将其存储在列表中。当您存储所有行时,假设您知道要删除的行,只需检查您不想存储的行,然后跳过它们。然后将列表内容写入文件。
//This is the file you are reading from/writing to
File file = new File("file.txt");
//Creates a reader for the file
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
//This is your buffer, where you are writing all your lines to
List<String> fileContents = new ArrayList<String>();
//loop through each line
while ((line = br.readLine()) != null) {
//if the line we're on contains the text we don't want to add, skip it
if (line.contains("TEXT_TO_IGNORE")) {
//skip
continue;
}
//if we get here, we assume that we want the text, so add it
fileContents.add(line);
}
//close our reader so we can re-use the file
br.close();
//create a writer
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//loop through our buffer
for (String s : fileContents) {
//write the line to our file
bw.write(s);
bw.newLine();
}
//close the writer
bw.close();