renameTo(File): This method is available in the java.io.File class of Java.
Syntax:
boolean java.io.File.renameTo(File dest)
This method takes one argument. This method renames the file denoted by this abstract pathname.
Parameters: One parameter is required for this method.
dest: The new abstract pathname for the named file.
Returns: true if and only if the renaming succeeded; false otherwise.
Throws:
1. SecurityException - If a security manager exists and its java.lang.SecurityManager.checkWrite(java.lang.String) method denies writing access to either the old or new pathnames
2. NullPointerException - If parameter dest is null
Approach 1: When no exception
Java
import java.io.File;public class FilerenameTo {public static void main(String[] args) {String pathname = "D:\\hello.txt";File file = new File(pathname);File dest = new File(pathname);System.out.println(file.renameTo(dest));}}
Output:
true
Approach 2: NullPointerException
Java
import java.io.File;public class FilerenameTo {public static void main(String[] args) {String pathname = "D:\\hello.txt";File file = new File(pathname);File dest = null;System.out.println(file.renameTo(dest));}}
Output
Exception in thread "main" java.lang.NullPointerException at java.base/java.io.File.renameTo(File.java:1401)
No comments:
Post a Comment