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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值