gpt4 book ai didi

java - File.delete() 删除目录中的文件失败

转载 作者:行者123 更新时间:2023-12-02 04:44:12 26 4
gpt4 key购买 nike

将文本文件写入目录后,我尝试删除 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.");
}
}

}
}
}
}

出了什么问题..??

最佳答案

您必须关闭每个 PrintWriter,即 pw.close() 必须位于“k”循环的末尾。

关于java - File.delete() 删除目录中的文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com