Метод удаления не удаляет - Java - PullRequest
0 голосов
/ 03 августа 2020

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

public class Laboratory {



public static void main(String[] args) throws FileNotFoundException,InterruptedException,IOException {
    
// paste your script here ;)
    
    String fileName = "record.txt";
    String filepath = "D:\\Programming\\Java\\Program - Script Test\\files\\" + fileName;
    
    String in = "";
    File file = new File(filepath);
    Scanner fscan = new Scanner(file);
    Scanner scan = new Scanner(System.in);
    PrintWriter pw = null;
    int linecount = 1;
    
    String content = "";
    
    // reads the file according to the given line count.
    
    for(int i = 0; i < linecount; i++) {
        
        content = fscan.nextLine();
        
    }
    
    // creates the template file.
    
    String tempPath = "D:\\Programming\\Java\\Program - Script Test\\files\\" + "temp.txt";
    
    String contentParts[] = content.split("\\|");
    
    System.out.println(content);
    System.out.println(contentParts[1]);
    System.out.println(contentParts[2]);
    
    System.out.print("change the name >> ");
    in = scan.nextLine();
    
    // edits the scanned content from the file.
    
    String finalContent = "|" + in + "|" + contentParts[2];
    
    System.out.println(finalContent);
    
    
    file = new File(filepath);
    fscan = new Scanner(file);
    
    // scans the original record and pastes it in a new template file.
    
    try {
        
        pw = new PrintWriter(new FileOutputStream(tempPath));
        
        if(linecount == 1) {
                
                content = fscan.nextLine();
                pw.println(finalContent);
                
                while(fscan.hasNextLine()) {
                    
                    content = fscan.nextLine();
                    pw.println(content);
                    
                }
                
        }
        
        else if (linecount > 1) {
            
            for (int i = 0; i < linecount - 1; i++) {
                
                content = fscan.nextLine();
                pw.println(content);
                
            }
            
            pw.println(finalContent);
            content = fscan.nextLine();
                
            while (fscan.hasNextLine()) {
                
                content = fscan.nextLine();
                pw.println(content);
                
            }
            
            
            
        }
        
        
        
    }
    
    catch(FileNotFoundException e) {
        
        System.out.println(e);
        
    }
    
    finally {
        
        pw.close();
        fscan.close();
        
    }
    
    
    
    // deletes the original record
    
    file.delete();
    
} // end of method

} // script test class end

Хотя я сделал тестовую программу, которая успешно удаляет файл.

public class delete {

public static void main(String[] args) {
    
    Scanner scan = new Scanner(System.in);
    File file = new File("helloworld.txt");
    
    String in;
    
    System.out.println("Press ENTER to DELETE file.");
    in = scan.nextLine();
    
    file.delete();
    

} // main method end

} // program end

Мой путь к файлу правильный, и я действительно не знаю, в чем проблема. Есть ли способ исправить это?

1 Ответ

1 голос
/ 03 августа 2020

Объяснение

file.delete() не выдает ошибку в случае неудачи. И здесь он потерпел неудачу, на что указывает его возвращаемое значение false.

Выполните вместо этого Files.delete(file.toPath()), и вы увидите точную причину ошибки, которая:

Exception in thread "main" java.nio.file.FileSystemException: D:\Programming\Java\Program - Script Test\files\record.txt: The process cannot access the file because it is being used by another process
       at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:92)
       at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
       at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
       at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:274)
       at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:105)
       at java.base/java.nio.file.Files.delete(Files.java:1146)
       at Laboratory.main(Laboratory.java:123)

Итак,

Процесс не может получить доступ к файлу, потому что он используется другим процессом

Поскольку у вас все еще есть сканер для открытия файла, вы заблокировать себя от удаления. Закройте сканер, и он заработает.

Ваш код открывает два (а не один) сканер на file, один в начале:

Scanner fscan = new Scanner(file);

, который вы используете во время начального l oop:

for (int i = 0; i < linecount; i++) {
    content = fscan.nextLine();
}

а затем позже вы создаете второй:

fscan = new Scanner(file);

, который вы также закрываете во время своего finally блока:

fscan.close();

Но вы никогда не закрывали первый сканер.

Решение

Добавить

fscan.close();

После начального l oop:

for(int i = 0; i < linecount; i++) {
    content = fscan.nextLine();
}
fscan.close();

и file.delete() будет успешным.

NIO

Как объяснялось, file.delete() - это плохо разработанный метод. Предпочитайте Files.delete(path).

В общем, если у вас нет веских причин использовать старую громоздкую библиотеку ввода-вывода файлов, не делайте этого. Вместо этого используйте NIO (Java 7 +).

...