【问题标题】:Renaming existing file in java在java中重命名现有文件
【发布时间】:2016-03-02 19:32:24
【问题描述】:

我正在编写一个基本的记事本程序,我希望它能够从命令行重命名文件。如果用户向扫描仪写入“重命名”,程序会根据输入更改笔记的文件名,例如-rename stack。但是如果用户输入两个新的笔记名称。程序会出现类似Invalid note name for renaming. It contains ' '. Enter one word. 的错误。如果现有文件使用建议的名称,程序将打印File already exists

我该怎么做:

-重命名堆栈
输入新的笔记名称?
stack over
用于重命名的注释名称无效。它包含“结束”。输入一个字
-重命名堆栈
输入新的笔记名称?
结束
文件已存在

这是我目前写的:

           ...
           else if (noteNameSplited[0].equals("rename")) {

            File file = new File(noteNameSplited[1]+".ncat");

            if(!file.exists()) {
                System.out.println("File does not exist !");
            }
            else {
                System.out.println("Enter the new note name");
                String data=scan.nextLine();
                File file2 = new File(data+".ncat");
                file.renameTo(file2);
            }
        }

【问题讨论】:

  • 阅读Files类的文档。

标签: java file


【解决方案1】:

这可能会对您有所帮助:

https://github.com/openstreetmap/osmosis/blob/master/osmosis-core/src/main/java/org/openstreetmap/osmosis/core/util/AtomicFileCreator.java#L50

    if (!tmpFile.exists()) {
        throw new OsmosisRuntimeException("Can't rename non-existent file " + tmpFile + ".");
    }

    // Delete the existing file if it exists.
    if (file.exists()) {
        if (!file.delete()) {
            throw new OsmosisRuntimeException("Unable to delete file " + file + ".");
        }
    }

    // Rename the new file to the existing file.
    if (!tmpFile.renameTo(file)) {
        throw new OsmosisRuntimeException(
                "Unable to rename file " + tmpFile + " to " + file + ".");
    }

【讨论】:

    【解决方案2】:

    您可以尝试以下方法:

    public boolean renameTo(File dest) {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(path);
            security.checkWrite(dest.path);
        }
        return fs.rename(this, dest);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 2023-03-21
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 2011-01-06
      • 2019-12-24
      • 1970-01-01
      相关资源
      最近更新 更多