簡體   English   中英

為什么File.delete()方法不起作用?

[英]Why is the method File.delete() not working?

我因嘗試發現該缺陷而沮喪了將近2天,因為registry.delete()方法不會刪除文件“ Registry.txt”。 我使用的是GUI,每次單擊JTable的行,然后單擊“ Ban”按鈕時,它都不會刪除文件“ Registry.txt”,也不會寫入! 但是,如果我從另一個類(例如具有main()方法的類main() ,它將正確清除。 想做的從Registry.txt中刪除一行,在另一個.txt文件中寫入所有不包含某個String名稱的行,然后將其重命名為Registry.txt 我不知道發生了什么。 下面是我的代碼:

ActionListener ban = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        int fila = table.getSelectedRow();
        String nombre = (String) modelo.getValueAt(fila, 0);
        modelo.removeRow(fila);
        try {
            removeUser(nombre);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
};
btnBanear.addActionListener(ban);

...

public void removeUser(String nombre) throws IOException {
    String lee = null;
    String usuario = "";
    CharSequence aux = nombre;
    try {
        registro = new File("Registro.txt");
        tempFile = new File("Registro1.txt");
        lector = new BufferedReader(new FileReader(registro));
        fw = new FileWriter(tempFile);
        writer = new BufferedWriter(fw);
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    } catch (NullPointerException e) {
        System.out.println(e.getMessage());
    }

    while ((lee = lector.readLine()) != null) {
        System.out.println(aux);
        if (lee.contains(nombre)) {
            continue;
        } else {
            writer.write(lee);
        }
    }
    lector.close();
    fw.close();
    writer.close();
    registro.delete();
}

我認為我們沒有足夠的數據來確切了解為什么會發生這種情況,但是我可以給您一些懷疑。

File.delete()引發四個可能的異常; 其中三個適用於此處。 NoSuchFileException (值得特別檢查), IOExceptionSecurityException NoSuchFileException派生自IOException ,無論如何都會被捕獲; 盡管您可能仍想抓住它,因為將其強制轉換為IOException會刪除相關數據。 一般情況下, SecurityException是安全管理器遇到的問題,它總是在基於Web的程序上發生。 我想知道您的文件是某種小應用程序還是現代的等效應用程序,即Web應用程序? SecurityExceptionRuntimeException ,因此您不必趕上它,但是您可以並且應該這樣做。 那將解釋世界。

最后,您還可以使用File.deleteIfExists() 如果實際存在要刪除的文件,則返回true;如果找不到該文件,則返回false。 值得一看,因為如果您的路徑傾斜並且在提供的位置找不到該文件,則不會刪除該文件。 有理由認為您的程序可能與您想像的目錄具有不同的工作目錄。 不過,這與檢查NoSuchFileException相同。

您甚至可以使用System.out.println(System.getProperty("user.dir"))檢查您的工作目錄。


我的錢在SecurityException或路徑錯誤上。 但是,如果我對此有誤,那么可以向我們展示您的其他按鈕代碼就很好了,因為那里也可能存在相關問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM