File oldfile = new File("C:\\NewText Document.txt");
File newfile = new File("C:\\Hello Buddy.txt");
if (oldfile.renameTo(newfile))
{
System.out.println("Rename succesful");
}
else
{
System.out.println("Rename failed");
}
I'm planning on developing it into a file normalizer, but I just want to get this done first. I've tried using the absolute path, makes no difference. Constantly returning "Rename Failed".
Use move method of Files class. Worked for me ;)
If you are using Java 7 then try this:
final File oldfile = new File("C:\\NewText Document.txt");
final File newfile = new File("C:\\Hello Buddy.txt");
final Path source = oldfile.toPath();
final Path dest=newfile.toPath();
try {
Files.move(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
FileChooser(); File oldfile = new File(fileName);
File newfile = new File(fileName.substring(0, 21) + "hello world.txt");
if (!oldfile.exists())
{
try
{
oldfile.createNewFile();
}
catch (IOException ex)
{
System.out.println(ex);
}
}
else
{
if (oldfile.renameTo(newfile))
{
System.out.println("Rename succesful");
}
else
{
System.out.println("Rename failed");
}
}
This is my new code, it works using a file chooser,but currently it only works if i choose the file from my desktop, hence the hardcoded substring.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.