Renaming a file in java

I tried to rename the file using the code I found here:

File newFile = new File(oldFile.getParent(), "new-file-name.txt"); Files.move(oldFile, newFile); 

Now I have done the following:

  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 a printout of the "made file", which means that there is an IO exception. However, the stack trace is not readable.

What is the reason for this?

+4
source share
3 answers

You can use the renameTo method, which already exists in the 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"); } 
+3
source

First of all, Java allows you to rename a file using the renameTo (File file) method, which exists in the java.io.File class.

First get a link to the file you want to rename. Second, call the renameTo () method on this link using the File argument. Suppose you have a file named file1.txt and you want to rename it file2.txt.

The lines of code below show how this is 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")); 
+1
source

If your file is located in the Windows shared folder, you may encounter problems using the File.renameTo() method.

A more robust solution is to use Apache Commons IO FileUtils.moveFile ()

+1
source

Source: https://habr.com/ru/post/1501774/


All Articles