Java stream locks file

0

I have this function that looks for a line in a file and removes it. The fact is that some stream remains open and does not allow me to rename the file.

import java.io.*;
import java.util.*;
import java.nio.file.Files;

public class Test {
    public void updateAttrib(MailInfo m) throws IOException {

        File inputFile = new File(Directory.directory+"\"+User.user+"\mails.txt");
        File tempFile = new File(Directory.directory+"\"+User.user+"\mailstmp.txt");

        if (tempFile.exists()) {
            try {
                RandomAccessFile raf=new RandomAccessFile(tempFile,"rw");
                raf.close();
                Files.delete(tempFile.toPath());
            } catch (IOException ioe) {}
        }

        FileReader fr = new FileReader(inputFile);
        FileWriter fw = new FileWriter(tempFile);
        try {
            BufferedReader reader;
            reader = new BufferedReader(fr);
            BufferedWriter writer;
            writer = new BufferedWriter(fw);

            try {

            String lineToRemove = m.getNombre();
            String currentLine;

                while((currentLine = reader.readLine()) != null) {
                    String trimmedLine = currentLine.trim();
                    if(trimmedLine.contains(lineToRemove)) continue;
                    writer.write(currentLine + System.getProperty("line.separator"));
                }

            } finally {
                reader.close();
                writer.close();
            }

        } catch (IOException ioe) {
        } finally {
            fr.close();
            fw.close();
        }

        boolean successful = tempFile.renameTo(inputFile);
    }
}
    
asked by Tretorn 18.08.2017 в 14:37
source

0 answers