Не удалось удалить файл на Java - PullRequest
0 голосов
/ 11 апреля 2019

файл не может быть удален и заменен по какой-либо причине.

Я хочу удалить только 1 строку из файла.Я нашел способ сделать это, создав временный файл, а затем записав каждую строку из исходного файла одну за другой, за исключением строки, которую я хочу удалить, и затем заменив исходный файл на временный, однако несмотря на то, что временный файл создан, исходный файл не можетбыть удалены и заменены по некоторым причинам.Я проверил, что файлы не открыты.

File inputFile = new File("epafes.txt");
File tempFile = new File("epafesTemp.txt");

BufferedReader reader2 = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String lineToRemove = del;
String currentLine;

while((currentLine = reader2.readLine()) != null) {
    // trim newline when comparing with lineToRemove
    String trimmedLine = currentLine.trim();
    if(trimmedLine.equals(lineToRemove)) continue;
    writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader2.close(); 
if (!inputFile.delete()) {
            System.out.println("Could not delete file");
            return;
        }

        //Rename the new file to the filename the original file had.
        if (!tempFile.renameTo(inputFile))
            System.out.println("Could not rename file");
        }

1 Ответ

0 голосов
/ 11 апреля 2019

Настоятельно рекомендуется использовать метод java.nio.file.Files#delete(Path) вместо File#delete.Прочитайте соответствующий вопрос .Кроме того, вам не нужно удалять файл и записывать в темп.Просто прочитайте текст, отфильтруйте его, как хотите, и, наконец, переписайте тот же файл с нуля.(Конечно, запись должна быть закрыта первой.)

Взгляните на этот пример:

public class ReadWrite {
    public static void main(String[] args) {
        File desktop = new File(System.getProperty("user.home"), "Desktop");
        File txtFile = new File(desktop, "hello.txt");
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(txtFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                if ("this should not be read".equals(line))
                    continue;
                sb.append(line);
                sb.append(System.lineSeparator());
            }
        } catch (IOException e) {
            System.err.println("Error reading file.");
            e.printStackTrace();
        }

        try (PrintWriter out = new PrintWriter(txtFile)) {
            out.write(sb.toString());
        } catch (IOException e) {
            System.err.println("Error writing to file.");
            e.printStackTrace();
        }
    }
}

Начальное содержимое hello.txt:

hello there
stackoverflow
this should not be read
but what if it does?
then my answer
is going to get downvotes

После запуска:

hello there
stackoverflow
but what if it does?
then my answer
is going to get downvotes

PS : Если вы работаете в Java 8+, взгляните на ресурсы для попытки и AutoClosable.

...