gpt4 book ai didi

java - 无法删除 NetBeans 中 servlet 中目录中的所有文件

转载 作者:行者123 更新时间:2023-12-01 19:09:43 26 4
gpt4 key购买 nike

我无法删除目录中的所有文件。它是 NetBeans 中的 servlet 应用程序。

 public void updateRootFile(String directorypath, String appID, String[] appName) throws IOException { 
FileInputStream finStream =null;
BufferedReader br = null;
OutputStreamWriter outStream = null;
FileInputStream fins = null;

String strLine="";

try {
File[] listOfFiles = fileLists("D:\\root\\");
for (int i = 0; i < listOfFiles.length; i++) {
String rootFiles = listOfFiles[i].getName();

File rootFile = new File("D:/root/"+rootFiles);
File copyFile = new File("D:/root1/"+rootFiles);

finStream = new FileInputStream(rootFile);

//String propertyStr = "root.label." + appID;
//properties.load(new InputStreamReader(finStream, Charset.forName("UTF-8")));
//String getAppName = properties.getProperty("root.label." + appID);
//String toUtf =new String(appName[i].getBytes("iso-8859-1"), "UTF-8") ;
//String oldChar = propertyStr + "=" + getAppName;
//String newChar = propertyStr + "=" + toUtf;

fins = new FileInputStream(rootFile);

br = new BufferedReader(new InputStreamReader(fins, "UTF-8"));
outStream = new OutputStreamWriter(new FileOutputStream(copyFile), "UTF-8");
while ((strLine = br.readLine()) != null) {
strLine = strLine.replace("hai", "haai");
outStream.write(strLine);
outStream.write("\r\n");
}
outStream.flush();
outStream.close();
br.close();
fins.close();
finStream.close();
}
} catch (Exception e) {
System.out.println("Excpetion : " + e);
}

File rootFileone = new File("D:/root");
boolean check= deleteDir(rootFileone);
}


public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=1; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
//if (!success) {
// return false;
// }
}
}
// The directory is now empty so delete it
return dir.delete();
}


private File[] fileLists(String directorypath) {
folder = new File(directorypath);
listOfFiles = folder.listFiles();
return listOfFiles;
}

我的文件夹中有 29 个 .properties 文件。但在此循环中,始终至少有一个文件保持未删除状态。因此我无法删除该文件夹。

最佳答案

如果文件已被其他程序打开,则无法删除该文件。

造成这种情况的可能原因有很多,无论是在您自己的代码内部还是外部。我假设您只在自己的代码中管理这些文件。您需要确保在 InputStream/OutputStreamReader/上调用 close() 方法Writer 位于您正在读取/写入文件的 try block 的 finally block 中。

因此,请确保遵循以下 Java IO 习惯用法:创建、使用和关闭 InputStream/OutputStreamReader/作家资源。

Writer writer = null;

try {
writer = new FileWriter(file); // Just an example. Can be any Writer.
writer.write(something);
// ...
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}

或者当您已经使用 Java 7 时:

try (Writer writer = new FileWriter(file)) {
writer.write(something);
// ...
}

try block 离开时,它将自动关闭 AutoCloseable 资源。

关于java - 无法删除 NetBeans 中 servlet 中目录中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8723269/

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