[英]Renaming existing file in java
我正在編寫一個基本的記事本程序,我希望它能夠從命令行重命名文件。 如果用戶將“重命名”寫入掃描儀,程序會根據輸入更改筆記的文件名,例如-rename stack
。 但是如果用戶輸入兩個新的筆記名稱。 程序將錯誤,如Invalid note name for renaming. It contains ' '. Enter one word.
Invalid note name for renaming. It contains ' '. Enter one word.
. 如果現有文件使用了建議的名稱,則程序將打印File already exists
。
我怎樣才能做到這一點:
-重命名堆棧
輸入新的筆記名稱?
堆疊
用於重命名的筆記名稱無效。 它包含“結束”。 輸入一個字
-重命名堆棧
輸入新的筆記名稱?
超過
文件已存在
這是我到目前為止所寫的:
...
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);
}
}
您可以嘗試以下操作:
public boolean renameTo(File dest) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
security.checkWrite(dest.path);
}
return fs.rename(this, dest);
}
這可能會幫助您:
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 + ".");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.