Я пытаюсь удалить текстовую строку из файла. Пока у меня это есть, но это дает мне некоторые проблемы. Он работает, если после исходного текста на строке ничего нет. Но если в текстовом файле у меня есть что-то после Барта, например, Барта Джонса, он не удалит строку, он просто оставит ее в покое. Пожалуйста помоги.Удаление строки текста с определенной строкой внутри нее
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil util = new FileUtil();
util.removeLineFromFile("booklist.txt", "bart");
}
} `
'String # contains' ... – m0skit0
@ m0skit0' содержит 'сам индекс вызова с другими плагинами ... –
Эффективность козыри удобочитаемости, за исключением случаев, наиболее чувствительных к производительности. Я бы использовал String #, поскольку он делает намерение понятным, а не indexOf. –