文件renameTo不起作用 [英] File renameTo does not work

查看:632
本文介绍了文件renameTo不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 JFileChooser 选择的文件名添加扩展名,但我无法让它工作。

I am trying to add an extension to the name of file selected by a JFileChooser although I can't get it to work.

这是代码:

final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File f = fc.getSelectedFile();
            String name =f.getAbsoluteFile()+".txt";
            f.renameTo(new File(name));
            FileWriter fstream;
            try {
                fstream = new FileWriter(f);
                BufferedWriter out = new BufferedWriter(fstream);
                out.write("test one");
                out.close();
            } catch (IOException ex) {
                Logger.getLogger(AppCore.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

我无法弄清楚为什么这不是工作。我也尝试使用getPath()和getCanonicalPath()但结果是一样的。该文件是在所选目录中创建的,但没有.txt扩展名。

I can't figure out why this doesn't work. I also tried using getPath() and getCanonicalPath() but the result is the same. The file is created at the directory selected, although without a ".txt" extension.

推荐答案

在我看来,你们所有人我想要做的是更改所选文件的名称,而不是重命名文件系统上的文件。在这种情况下,您不使用 File.renameTo 。您只需更改文件即可。类似下面的内容应该有效:

It seems to me that all you want to do is to change the name of the file chosen, as opposed to renaming a file on the filesystem. In that case, you don't use File.renameTo. You just change the File. Something like the following should work:

        File f = fc.getSelectedFile();
        String name = f.getAbsoluteFile()+".txt";
        f = new File(name);

File.renameTo 尝试重命名文件系统上的文件。例如:

File.renameTo attempts to rename a file on the filesystem. For example:

File oldFile = new File("test1.txt");
File newFile = new File("test2.txt");
boolean success = oldFile.renameTo(newFile); // renames test1.txt to test2.txt

在这三行之后,成功 true 如果文件 test1.txt 可以重命名为 test2.txt false 如果重命名不成功(例如 test1.txt 不存在,在另一个进程中打开,权限被拒绝等等。)

After these three lines, success will be true if the file test1.txt could be renamed to test2.txt, and false if the rename was unsuccessful (e.g. test1.txt doesn't exist, is open in another process, permission was denied, etc.)

我会冒险猜测你正在尝试的重命名是失败的,因为你正在尝试重命名目录(您使用 JFileChooser 并使用 DIRECTORIES_ONLY 选项)。如果您有使用此目录中的文件的程序,或者在其中打开命令提示符,它们将反对重命名此目录。

I will hazard a guess that the renaming you are attempting is failing because you are attempting to rename a directory (you are using a JFileChooser with the DIRECTORIES_ONLY option). If you have programs using files within this directory, or a Command Prompt open inside it, they will object to this directory being renamed.

这篇关于文件renameTo不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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