Hanno Opperman
Hanno Opperman

Reputation: 143

Java: Copying a File (using Path) to a directory and renaming a file with the same name

I'm new to Java and working on a project to improve my skills and need some help.

I have a file, lets call it tools.extension, it is going to have to go to a directory that already has a tools.extension file. I want my code to check that tools.extension exists, and if it does, to rename it to tools(currentdate).extension.

So I tried this to test the logic:

Scanner myS = new Scanner(System.in);
        Path path = Paths.get(myS.nextLine());
        Path file = Files.createFile(path);
        Path path1 = Paths.get(myS.nextLine());
        Path file1 = Files.createFile(path1);

       if (file.getFileName() == file1.getFileName())

       {
           System.out.println("file already exists");
       }

       else
       {
           System.out.println("File doesn't already exist");
       }

       Files.delete(file);
       Files.delete(file1);

But of course then I realized that there is going to be an exception somewhere, but I just wanted to try this to check my logic.

And I always get file doesn't already exist

not even if I create two text.txt files in different directories. It doesn't see them as having the same name, even though when I print getFileName(), both of them are!

Could someone give me some advice or point me towards a tutorial that'll help me?

Thank you ever so much!

EDIT:

Thank so much for reminding me of the .equals, it is working!

I just have another question, how do I go about renaming file or file1? Them being paths I don't know of a way.

Should I use a toFile() method and then use renameTo()?

Upvotes: 0

Views: 696

Answers (3)

ben75
ben75

Reputation: 28706

I don't know what you have behind Files.createFile(path); but few important things about File API :

File.exists() must be used to check the existence of a file in the File System.

The File.delete() returns a boolean telling you if the call was successful or not.

You can create a File object as you wan't, but it don't implies that the file while be created on the File System.

To create a file on the File System you need to invoke : File.createNewFile() . And once again this method returns a boolean telling you if the creation was successful or not.

The File.renameTo(anotherFile) can be used to rename a file. And one again it retuns a boolean telling you is the renaming was succesfull or not.

A common mistake while playing with files is to forgot checking the result of all those file system operations... so don't forget it.

Upvotes: 0

Zaz Gmy
Zaz Gmy

Reputation: 4356

just use

if(file.getFileName().equals(file1.getFileName())){
  //file exist
  }

Upvotes: 0

Andremoniy
Andremoniy

Reputation: 34900

This if (file.getFileName() == file1.getFileName()) is the mistake.

You should compare strings using .equals(...) method.

Upvotes: 1

Related Questions