Renaming file in java


Question:

I tried to rename a file, using code I found here:
File newFile = new File(oldFile.getParent(), "new-file-name.txt");  Files.move(oldFile, newFile);  
Now, what I did was this:
  private void stFiles() {      System.out.println("sorting");      File f = new File (getName());      name = getName() + counter.toString();      System.out.println(f.getName());      File newFile = new File(f.getParent(), getName()+ ".jpg");      try {          Files.move(f, newFile);      } catch (IOException ex) {          System.out.println("made file");      }      counter +=1;  }  
Now, I get the "made file" print, Which means there is an IO-Exception. The Stack Trace, however, is not readable.
What can be the reason for this?


Solution:2

You can use the renameTo method which already exists in File object as shown below:
File myOriginalFile=new File("myOriginalFile.txt");      File myChangedFile=new File("myChangedFile.txt");            if(myOriginalFile.renameTo(myChangedFile)){          System.out.println("Rename operation succesful");      }else{          System.out.println("Rename operation failed");      }  


Solution:3

First of all, Java allows you to rename a file by using the renameTo(File file) method which is there in the java.io.File class.
First, obtain a reference to the file that you want to rename. Second, invoke the renameTo() method on that reference using a File argument. Suppose you have a file named file1.txt and you want to rename it file2.txt.
The code lines below show how it's done:
//Obtain the reference of the existing file  File oldFile = new File("file1.txt");     //Now invoke the renameTo() method on the reference, oldFile in this case  oldFile.renameTo(new File("file2.txt"));  


Solution:4

If your file is on a Windows share, you may face issues using the File.renameTo() method.
A more robust solution is to use Apache Commons IO FileUtils.moveFile()

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »