【发布时间】:2014-08-29 15:41:21
【问题描述】:
我有一个目录,我以编程方式(在 Java 中)执行递归解压缩(这似乎可行),但最后我留下了一个包含很多子目录和文件的目录。每次运行此方法时,我都想从头开始,因此我总是删除临时目录中存在的文件夹及其剩余文件和子目录。
root = new File(System.getProperty("java.io.tmpdir")+ File.separator + "ProductionTXOnlineCompletionDataPreProcessorRoot");
if(root.exists()){
try {
FileUtils.deleteDirectory(root);
} catch (IOException e) {
e.printStackTrace();
}
}
if(root.mkdir()){
rawFile = createRawDataFile();
}
我从 FileUtils.deleteDirectory 收到一个非常奇怪的错误。
14:55:27,214 ERROR [stderr] (Thread-3 (HornetQ-client-global-threads-2098205981)) java.io.IOException: Unable to delete directory C:\Users\Admin\AppData\Local\Temp\ProductionTXOnlineCompletionDataPreProcessorRoot\ProductionTXOnlineCompletionDataPreProcessor8718674704286818303.
似乎认为我的目录末尾有一个句号(它没有,所以它不能删除它也就不足为奇了)。有时,此错误会出现在子目录中的文件夹上。有人见过这个吗?
我正在使用 Commons IO 2.4 jar。
编辑我已经确认目录没有句点,所以除非它们不可见,否则我不知道为什么该方法会认为有句点。我给方法提供的文件路径是在将它作为参数提供之前设置的,正如任何人都可以看到的那样 - 它最后没有句点。
我在 Windows 7 上运行该程序。
编辑这是我用于递归解压缩的代码:
private void extractFolder(String zipFile) throws IOException
{
int BUFFER = 2048;
File file = new File(zipFile);
ZipFile zip = null;
String newPath = zipFile.substring(0, zipFile.length() - 4);
BufferedOutputStream dest = null;
BufferedInputStream is = null;
try{
zip = new ZipFile(zipFile);
Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
while (zipFileEntries.hasMoreElements())
{
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
File destinationParent = destFile.getParentFile();
destinationParent.mkdirs();
if (!entry.isDirectory())
{
is = new BufferedInputStream(zip
.getInputStream(entry));
int currentByte;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(destFile);
dest = new BufferedOutputStream(fos, BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
}
if (currentEntry.endsWith(".zip")){
// found a zip file, try to open
extractFolder(destFile.getAbsolutePath());
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(dest!=null) {dest.close();}
if(is!=null) {is.close();}
zip.close();
}
}
我把原压缩包放到根目录下,然后递归解压。
这是显示的相关代码:
downloadInputStreamToFileInRootDir(in, rawFile);
try {
extractFolder(rawFile.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
}
我刚刚注意到我最初使用 rawFile.getCanonicalPath()(rawFile 在第一个代码摘录中设置)作为 extractFolder 的参数,然后切换到 destFile.getAbsolutePath() ...也许这与它有关.对此进行测试的问题在于问题不是确定性的。它有时会发生,有时不会。
【问题讨论】:
-
是另一个线程/进程在您尝试删除目录内容时修改它们吗?
-
它在本地服务器(Wildfly)上运行,我的程序是唯一在它上面运行的程序。程序本身只在一个线程上。这很奇怪,因为该参数显然没有句点(它是在调用方法 deleteDirectory 之前设置的。)但它抱怨目录有句点。我认为这是一个错误,但我不会排除我丢失某些东西的可能性。
-
句点不在您创建的目录名称上,而是在嵌套目录上。
-
好点,jtahlborn。我认为问题出在我为每个递归调用提供的参数上。
标签: java io fileutils apache-commons-io