Java.Streams.What methods of the File class do you know?

Here’s a categorized list of the most commonly used methods of the File class:


📁 File Creation & Deletion

MethodDescription
createNewFile()Creates a new empty file if it doesn’t exist
delete()Deletes the file or directory
deleteOnExit()Deletes file when JVM exits

📂 Directory Management

MethodDescription
mkdir()Creates a single directory
mkdirs()Creates directories including parent folders
list()Returns an array of file/directory names
listFiles()Returns an array of File objects for contents
isDirectory()Checks if it’s a directory
isFile()Checks if it’s a file

🔄 Renaming / Moving

MethodDescription
renameTo(File dest)Renames or moves the file/directory

📏 File Information

MethodDescription
length()Gets file size in bytes
exists()Checks if the file or directory exists
canRead()Checks if it’s readable
canWrite()Checks if it’s writable
canExecute()Checks if it’s executable
isHidden()Checks if it’s hidden
lastModified()Gets last modification time
setLastModified(long time)Sets last modification time
setReadOnly()Makes the file read-only

🧭 Path Methods

MethodDescription
getName()Gets name (e.g., file.txt)
getPath()Gets path as provided
getAbsolutePath()Gets full path from root
getCanonicalPath()Gets resolved (clean) path
getParent()Gets parent directory as string
getParentFile()Gets parent as a File object
toURI()Converts to a URI
toPath()Converts to a Path (Java NIO)

🧪 Quick Example

File file = new File("example.txt");

if (!file.exists()) {
    file.createNewFile();
}
System.out.println("Name: " + file.getName());
System.out.println("Size: " + file.length());
System.out.println("Parent: " + file.getParent());
System.out.println("Exists? " + file.exists());

🧵 TL;DR: File Class = File Metadata + Path Operations

CategoryExamples
File creation/deletioncreateNewFile(), delete()
Metadataexists(), length(), canRead()
Directorymkdirs(), listFiles(), isDirectory()
PathsgetPath(), getAbsolutePath(), toPath()
ModifierssetReadOnly(), setLastModified()
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.