Java File constructors and names
Build a classic File pathname and inspect its filename and parent.
A simple example
File constructors and names
- Start with Path notes/a.txt
- Do this Read its final component
- Result a.txt
Syntax
public File(String pathname)
JDK 21 declarations (9)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaLabel a receipt before it is saved
A cashier chooses a receipts folder and types a name for a new invoice. The preview needs to show the filename and its parent before the printer saves any data.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
File folder = new File("receipts");
File invoice = new File(folder, "order-28.txt");
System.out.println(invoice.getName());
System.out.println(invoice.getParent());
System.out.println(folder.equals(invoice.getParentFile()));
System.out.println(invoice.getPath().equals(invoice.toString()));
}
}
order-28.txt receipts true true
The string forms describe the pathname. The parent object can be passed to other File methods.
Handle a filename with no parent
An upload form sometimes supplies just the filename from a student's computer. A preview must still print that filename even when there is no directory to show beside it.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
File scan = new File("sketch.png");
System.out.println(scan.getName());
System.out.println(scan.getParentFile() == null);
}
}
sketch.png true
A one-name relative File has no parent object.
Locate a rehearsal score
The choir stores each score inside a season folder. Build the nested path and read its final name for the screen.
What to watch for
A File can describe a nonexistent entry. Both parent accessors can return null for a relative name without a parent.