Java renameto无效_Java重命名文件renameTo在windows下失败原因分析

在用Java压缩文件时,将原始数据xxx.dat压缩为xxx.tmp的临时文件,压缩完成以后再将xxx.tmp文件重命名为xxx.z。可怜我在linux下测试成功,而在windows下则一直没有反应。

也看了一些其他类似的情况,因为是同目录重名,不存在跨盘符的问题。

于是仔细看了下代码,猜测是文件是被占用导致。问题代码如下:for (File dataFile : files) {

File compressTempFile = new File(dataFile.getAbsolutePath() + ".tmp");

File compressFile = new File(dataFile.getAbsolutePath() + ".z");

if (this.fileRewrite && compressFile.exists()) {

compressFile.delete();

}

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(compressTempFile));

InputStream is = new FileInputStream(dataFile);

try {

if (dataFile.getName().contains("-bar")) {

int len = doCompress(is, bos, barCellSize, compressBarBatch, compressBarRecordSize);

if (len > max[0]) {

max[0] = len;

}

} else {

int len = doCompress(is, bos, tickCellSize, compressTickBatch, compressTickRecordSize);

if (len > max[1]) {

max[1] = len;

}

}

//compressTempFile.renameTo(compressFile);

//window下错误,此时文件尚未关闭,在windows被占用,linux下则不存在该问题。

} finally {

ResourceUtil.close(is);

ResourceUtil.close(bos);

}

//正确,文件已经关闭

compressTempFile.renameTo(compressFile);

}


版权声明:本文为weixin_35900054原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。