Reputation: 61
Here I have a made a Java program to rename a text file . I haven't used the renameTo() method because it just creates another file of same name with empty content . I have instead created two file objects and tried to copy the contents from the first file to the second file (creating it if not exists) which is succeeded but after that when I got to delete the old file it fails. Please let me know any answers. Here's the whole source code.
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class FileRenamer {
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.println("Enter the name of the text file to be renamed");
String oldname = inp.nextLine();
File oldFile = new File("C:\\Java\\" + oldname + ".txt");
Scanner reader = new Scanner(new File("C:\\Java\\"+oldname+".txt"));
System.out.println("Enter the new File name");
String newname = inp.nextLine();
File newFile = new File("C:\\Java\\"+ newname + ".txt");
if (!newFile.exists()){
newFile.createNewFile();
}
oldFile.renameTo(newFile);
FileWriter newf = new FileWriter("C:\\Java\\"+ newname + ".txt");
while (reader.hasNextLine()) {
String rename = reader.nextLine();
newf.write(rename+"\n");
}
newf.flush();
newf.close();
if (oldFile.delete()){
System.out.println("File renamed");
}
else {
System.out.println("File renaming failed");
}
}catch (Exception e ){
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 154
Reputation: 1896
You don't need to create a new file and copy the content. That operation is too tedious. Your FileRenamer
can be easily implemented if you use Java New IO classes (from package java.nio.file
).
Here an example of implementation, just to give you an idea. I tested it and it works perfectly fine:
import java.nio.file.*;
import java.io.IOException;
import java.util.Scanner;
public class FileRenamer {
public static void main(String ... args) {
try {
Scanner inp = new Scanner(System.in);
System.out.println("Enter the name of the text file to be renamed");
String oldname = inp.nextLine();
Path oldFile = Paths.get("C:\\Java", oldname + ".txt");
System.out.println("Enter the new File name");
String newname = inp.nextLine();
Path newFile = Paths.get("C:\\Java", newname + ".txt");
Files.move(oldFile, newFile, StandardCopyOption.REPLACE_EXISTING);
}
catch(IOException ex) {}
}
}
Upvotes: 0
Reputation: 364
You´ve initialised oldFile:
File oldFile = new File("C:\\Java\\" + oldname + ".txt");
Then you rename oldFile:
oldFile.renameTo(newFile);
if (oldFile.delete())
still refers to the old path, which then no longer exists, because you renamed the file. (you have build the old path with File oldFile = new File("C:\\Java\\" + oldname + ".txt");
)
Upvotes: 2