问题描述:

I am programming basic notepad program.This program contains rename method. If user write "rename" to scanner. Program is changing note name according to input like rename stack. But if user enter two new notename. Programm will error like "Invalid note name for renaming. It contains ' '.Enter one word ". If new note name is the same name with existing file. Program will print " File already exists". How can i do theese ?

-rename stack

Enter new note name ?

stack over

Invalid note name for renaming. It contains ' '.Enter one word

-rename stack

Enter new note name ?

over

File already exists

enter code here

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);

}

}

网友答案:

You can try the following:

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

Full code here: http://code.openhub.net/file?fid=wJA8QKQ1K6QdkiVbFZrm3TFdLXE&cid=v2q_WSdZ-fw&s=Renaming%20existing%20file%20in%20java&fp=275914&mp,=1&ml=1&me=1&md=1&projSelected=true#L1236

网友答案:

This may help you:

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 + ".");
    }
相关阅读:
Top