0

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.

Papbad
  • 163
  • 2
  • 13
  • Generally the process of moving a file means you copy it to a new location, and delete the old file. – sleepToken Mar 02 '20 at 16:01
  • 1
    I'm not quite sure what you mean, but it *sounds* as if you want to change the content of an existing `File` object to point to another. That's not possible, that class is immutable by design (i.e. you can't change what a `File` points to, you can just create a new `File` object with a different value). But since `File` is such a light-weight object (it's basically a wrapper around a `String`) creating a new `File` instance isn't expensive, so don't worry about it. – Joachim Sauer Mar 02 '20 at 16:20

2 Answers2

1

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.

0

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.");
}
Jason
  • 5,154
  • 2
  • 12
  • 22