File.delete()无法删除目录中的文件

时间:2015-04-23 07:36:42

标签: java io

将文本文件写入目录后,我试图删除PrintWriter写的空文件。

File.delete()函数无法删除该文件。以下是编写和删除的代码。

private static void writeFile(ArrayList<ArrayList<String>> listRowVal, String szOutputDir, ArrayList<String> listHeader){     
       PrintWriter pw  = null;         
       try {                    
           ArrayList<String> listCells = listRowVal.get(0);            
           int iCells = listCells.size();          
           for(int k=0; k<iCells; k++){
               String language = listHeader.get(k);
               String szFileName = "files_"+ language +".csv";                 
               pw  = new PrintWriter(new FileWriter(szOutputDir + File.separator + szFileName));               
               for(ArrayList<String> listNCRCellVal : listRowVal){
                   String szVal = listNCRCellVal.get(k);
                   if(szVal != null && szVal.trim().length() > 0){
                       pw.println(szVal);
                   }
                   pw.flush();                
               }                   
           }           

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        try {
            if(pw != null){
             pw.close();
             pw = null;
            }
            //System.gc();
            deleteEmptyFiles(szOutputDir);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

   }
 private static void deleteEmptyFiles(String szDirPath) {
        File file = new File(szDirPath);
        if (file.isDirectory()) {
            String[] files = file.list();
            if (files.length > 0) {
                for (String szFileName : files) {
                    File deleteFile = new File(szDirPath + File.separator + szFileName);
                    if (deleteFile.length() == 0) {                     
                        //deleteFile.setWritable(true, false);
                        boolean bdeleted = deleteFile.delete();                     
                        if(bdeleted){
                            System.out.println(deleteFile.getName() + " deleted.");                         
                        }
                    }

                }
            }
        }
    }

出了什么问题.. ??

1 个答案:

答案 0 :(得分:2)

您必须关闭每个 PrintWriter,即pw.close()必须位于&#34; k&#34;循环。