Understanding Files and Directories in Java
java.io.File to java.nio.file reflects how file I/O became faster, safer, and more modern.
In Java, a file represents a data storage entity (text, image, binary, etc.), while a directory is a folder that can contain files or subdirectories.
The java.io.File class allows us to interact with the file system easily.
isFile() or isDirectory().
import java.io.File;
public class FileCheck {
public static void main(String[] args) {
File f = new File("sample.txt");
if (f.isFile()) System.out.println("It is a file.");
else if (f.isDirectory()) System.out.println("It is a directory.");
else System.out.println("Path does not exist.");
}
}
π Hover to view output
import java.io.File;
import java.io.IOException;
public class FileCreateDelete {
public static void main(String[] args) {
try {
File file = new File("demo.txt");
if (file.createNewFile())
System.out.println("File created: " + file.getName());
else
System.out.println("File already exists.");
if (file.delete())
System.out.println("File deleted successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
π Hover to view output
import java.io.File;
public class DirectoryList {
public static void main(String[] args) {
File dir = new File(".");
String[] files = dir.list();
for (String name : files)
System.out.println(name);
}
}
π Hover to view output
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("hello.txt");
fw.write("Welcome to NBKRIST JavaHub!");
fw.close();
BufferedReader br = new BufferedReader(new FileReader("hello.txt"));
System.out.println(br.readLine());
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
π Hover to view output
Introduced in Java 7, the java.nio.file package modernizes file handling with Path and Files classes.
It provides methods for reading, writing, copying, moving, and deleting files efficiently.
import java.nio.file.*;
import java.io.IOException;
public class NIOExample {
public static void main(String[] args) throws IOException {
Path p = Path.of("nbkrist.txt");
Files.writeString(p, "NBKRIST: JavaHub Rocks!");
String content = Files.readString(p);
System.out.println(content);
}
}
π Hover to view output
Files and Path for better readability, performance, and modern file operations.java.io.File helps create, read, and manage files.isFile() and isDirectory() differentiate file types.Files and Path for powerful file handling.