Papbad
Papbad

Reputation: 163

How to change pathname of file in Java?

I have a Save As... function in my text editor. I would like to do a Save As, save to a new file, but then my permanent file to save to should now always be this new file. So when I click my other button, Save, instead of saving to the previous location is will continue to save to the location which was selected with JFileChooser.

I have a File object called currentFile which should link to the file chosen via Save As. I am currently making sure of that by creating a file called fileName in my button action performed function, and then setting the currentFile to that file

    File fileName = new File(fileChoice.getSelectedFile() + ".txt");
    currentFile = fileName;

I was wondering if I could achieve the same thing without creating new file..? It appears to me that the new file creation follows the File(String pathname) constructor, yet there seems to be no method to set pathname of the file.

Upvotes: 0

Views: 1317

Answers (2)

Matteo Gallinucci
Matteo Gallinucci

Reputation: 38

You can't change File path, because as you can read in the docs and in this answer:

"Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change"

so you need to create another instance of File.

Also renameTo() method uses another instance of File as parameter to change the path

File fileToMove = new File("path/to/your/oldfile.txt");
boolean isMoved = fileToMove.renameTo(new File("path/to/your/newfile.txt"));

You can also read this article, there are several ways to rename or move files.

Upvotes: 1

Jason
Jason

Reputation: 5246

You're asking to change the path name but what you really want is to move the file. Files#move does this for you.

Path path = Paths.get("my", "path", "to", "file.txt");

Path moveToPath = Paths.get("my", "path", "to", "moved", "file.txt");

Path moveResult = Files.move(path, moveToPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.ATOMIC_MOVE);

if (!moveToPath.equals(moveResult)) {
    throw new IllegalStateException("Unable to move file to requested location.");
}

Upvotes: 0

Related Questions