java - 为什么我的文件不会自行重命名?

标签 java android file

我正在开发一个 Android 应用程序,我想重命名一个文件。问题是它没有重命名:

 File f = adapter.getItem(i);
 File file = new File(f.getAbsolutePath(), "helloworld");
 if (f.renameTo(file)) {
 Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
 }

解决方案大感谢@S.D.(见评论)

File f = adapter.getItem(i);
     File file = new File(f.getParent(), "helloworld");
     if (f.renameTo(file)) {
     Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
     }

最佳答案

我认为问题在于:

File f = adapter.getItem(i);

使用一些File f,说f对应的地方:user2351234/Desktop。然后,您可以:

 File file = new File(f.getAbsolutePath(), "helloworld");

上面写着制作一个File文件,其中file对应于:user2351234/Desktop/helloworld。接下来,您调用:

f.renameTo(file)

它试图将 fuser2351234/Desktop 重命名为 user2351234/Desktop/helloworld,这没有意义,因为为了user2351234/Desktop/helloworld 存在,user2351234/Desktop 必须存在,但由于操作它不再存在。

我的假设可能不会是原因,但是来自Why doesn't File.renameTo(…) create sub-directories of destination? ,显然 renameTo 如果子目录不存在,返回 false

如果您只想更改文件的名称,请执行以下操作:

File f = adapter.getItem(i);
String file = f.getAbsolutePath() + "helloworld";
f = new File(file);

编辑:
我提出的解决方案应该可行,但如果我关于您的方法为何不起作用的假设不正确,您可能希望看到此 answer来自 Reliable File.renameTo() alternative on Windows?

关于java - 为什么我的文件不会自行重命名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18039404/

相关文章:

android - 如何在 ADT 的图形布局编辑器中调试自定义 View

android - 将 volley 请求的结果使用到 AutocompleteAdapter 中

java - 在 Java 中将文件从一个目录复制到另一个目录

java - 包含所有元素的二维数组的深拷贝

java - 支柱2 : return to calling page

java - 批处理文件到java测试

c# - File.GetFiles 或 File.EnumerateFiles 锁定文件?

java - 使用JAVA无密码连接SYSDBA

android - 验证对话框输入

macos - MAC : How to merge folder so that we only overwrite when source files is newer than destination files?