jeudi 5 novembre 2015

Why cant I change the the file extension of a desired file in java?

I cant understand why my code refuses to change the file extension of my txt file to java.

Here's my code:

public static void main(String[] arg) {

 File file  = new File("file.txt"); //File I want to change to .java
 File file2 = new File(""); 

 boolean success = file.renameTo(file2); //boolean to check if successful

 if (success == true)
     System.out.println("file extension change successful");

     System.out.println("File extension change failed");

}// main

It always prints "file extension failed" each time and I honestly do not understand why. I'm starting to suspect it might be the permissions on my computer. The compiler I use is Eclipse.


THE CAUSE OF THE PROBLEM: I had placed the file I wanted to change, file.txt, in the package folder inside my project folder. C:\Users\Acer\workspace\MyProjectName\src\MyPackageName. As a consequence the file could not be found by the system.

THE SOLUTION: I simply moved the file, file.txt, into the main project folder; C:\Users\Acer\workspace\MyProjectName and this fixed the problem. When I run my program it returns

file extension change successful


Thank you all for your help. I really appreciate it.

Aucun commentaire:

Enregistrer un commentaire