无法删除Java中的文件 - 无法弄清楚我缺少的是什么

时间:2011-07-19 13:41:33

标签: java

我在我的应用程序之外尝试了这个代码并且效果很好,但我不能为我的生活弄清楚为什么这不会删除inputFile并重命名tempFile。

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {                                      
File inputFile = new File("c:\\test.csv");
File tempFile = new File("c:\\temp.csv");
    try
    {
        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

        String lineToRemove = tf_custID.getText() + "," + tf_custName.getText() + "," + tf_contactName.getText() + "," + tf_lastContact.getText() + "," + tf_phoneNumber.getText() + "," + tf_shippingAddress.getText() + "," + tf_shippingAddress2.getText() + "," + tf_City.getText() + "," + cb_State.getSelectedItem().toString() + "," + tf_Zipcode.getText() + ","; 
        String currentLine;

        while((currentLine = reader.readLine()) != null) 
        {
            // trim newline when comparing with lineToRemove
            String trimmedLine = currentLine.trim();
            //System.err.println(trimmedLine);
            //System.err.println(lineToRemove);
            if(trimmedLine.equals(lineToRemove)) continue;
            writer.write(currentLine);
            writer.write("\n");                
        }


        reader.close();            
        writer.close();

        } 
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }


    if(inputFile.delete())
    {
        System.out.println("** Input File Deleted Successfully, renaming temporary file. **");
        boolean successful = tempFile.renameTo(inputFile);
        if(successful)
        {
            System.out.println("** Temporary File Renamed Successfully");
        }
        else
        {
            System.err.println("** Temporary File Rename Failed");
        }
    }
    else
    {
        System.err.println("** Unable to Delete Input File **");            
    }

} 

先谢谢,我只是被卡住了。

1 个答案:

答案 0 :(得分:0)

删除之前,应确保文件存在,以便更好地报告问题。 我没有看到你打电话给inputFile.createNewFile(); 而且我相信如果删除是假的,可能有几个可能的原因但很可能是因为文件不存在所以试试..

if (inputFile.exists()){
   doDelete(inputFile); //<-- your delete code.
}else{
   System.out.println(String.format("Oops I thought the file [%s] existed", inputFile));
}

同时 ...

我会查看Commons-IO以帮助解决java中文件IO所需的样板代码。这是一个很好的图书馆。