File.renameTo()失败 [英] File.renameTo() fails

查看:716
本文介绍了File.renameTo()失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有eclipse插件jface应用程序。
线程通过BufferedWriter写入文件。
写完后我关闭缓冲区,然后尝试重命名文件。

I have eclipse plugin jface application. A thread writes file via BufferedWriter. After writing is done I close the buffer after that I try to rename the file.

但有时候文件没有被重命名!

But sometimes file is not renamed!

我试图在一对夫妇之间添加一些Thread.Sleep(BIG_NUMBER)重试这没有帮助。

I tried to add some Thread.Sleep(BIG_NUMBER) between couple of retries this didn't help.

看起来该文件正在获得某种锁定。 (当我杀死jvm时,我可以重命名文件)。

It looks like the file getting some kind of lock. (when I kill the jvm I can rename the file).

我能做些什么吗?

操作系统:Windows XP,Windows 7
JAVA版本:1.5

OS: Windows XP, windows 7 JAVA version: 1.5

推荐答案

File.RenameTo()依赖于平台并依赖在成功重命名文件的几个条件下,更好的选择是使用

File.RenameTo() is platform dependent and relies on a few conditions to be met in order to succesfully rename a file, a better alternative is using

Path source = currentFile.toPath();
try {
     Files.move(source, source.resolveSibling(formattedName));
} catch (IOException e) {
     e.printStackTrace();
}

了解更多这里

来自javadocs:

From the javadocs:


此方法行为的许多方面本质上都是
平台相关的:重命名操作可能无法移动
文件从一个文件系统到另一个文件系统,它可能不是原子的,如果目标为抽象路径名
的文件已存在,则
可能不会成功。应始终检查返回值以确保
重命名操作成功。

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

请注意,Files类定义移动方法以独立于平台的方式移动或重命名文件。

Note that the Files class defines the move method to move or rename a file in a platform independent manner.

这篇关于File.renameTo()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆