Junior
What methods of the File class do you know?
sobes.tech AI
Answer from AI
getName(): Returns the name of the file or directory.getPath(): Returns the path to the file or directory specified when creating theFileobject.getAbsolutePath(): Returns the absolute path to the file or directory.getParent(): Returns the path to the parent directory ornullif the file or directory is the root of the file system.exists(): Checks if the file or directory exists.isDirectory(): Checks if the object is a directory.isFile(): Checks if the object is a file.length(): Returns the size of the file in bytes.canRead(): Checks if the file is readable.canWrite(): Checks if the file is writable.canExecute(): Checks if the file is executable.createNewFile(): Creates a new empty file.delete(): Deletes the file or directory.list(): Returns an array of strings representing the names of files and directories in the directory.listFiles(): Returns an array ofFileobjects representing the files and directories in the directory.mkdir(): Creates a directory.mkdirs(): Creates a directory, including all necessary parent directories.renameTo(File dest): Renames the file or directory to the specified location.lastModified(): Returns the last modified time of the file or directory.setLastModified(long time): Sets the last modified time of the file or directory.setReadOnly(): Sets the "read-only" flag.setWritable(boolean writable): Sets the writable flag.setReadable(boolean readable): Sets the readable flag.setExecutable(boolean executable): Sets the executable flag.toURI(): Converts the file path to a URI.toURL(): Converts the file path to a URL (deprecated, better to usetoURI()).
Example usage:
import java.io.File;
import java.io.IOException;
// Example of creating a File object and checking its properties
public class FileExample {
public static void main(String[] args) {
File file = new File("my_file.txt");
try {
// Create a new file if it does not exist
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
// Output file information
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("Parent directory: " + file.getParent());
System.out.println("Is a file: " + file.isFile());
System.out.println("Is a directory: " + file.isDirectory());
System.out.println("File size in bytes: " + file.length());
System.out.println("Can read: " + file.canRead());
System.out.println("Can write: " + file.canWrite());
// Delete the file
// if (file.delete()) {
// System.out.println("File deleted successfully.");
// } else {
// System.out.println("Failed to delete the file.");
// }
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}