Library contents

Java File constructors and names

Build a classic File pathname and inspect its filename and parent.

A simple example

File constructors and names

  1. Start with Path notes/a.txt
  2. Do this Read its final component
  3. Result a.txt
The directory portion is notes and the last name is a.txt.

Syntax

Java 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.java

Label 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.

First output lineorder-28.txt
Main.java
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()));
    }
}
Output
order-28.txt
receipts
true
true

The string forms describe the pathname. The parent object can be passed to other File methods.

Advertisements

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.

First output linesketch.png
Main.java
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);
    }
}
Output
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.

Givenspring / alto.txt
Worked resultalto.txt

What to watch for

A File can describe a nonexistent entry. Both parent accessors can return null for a relative name without a parent.

Documentation for File constructors and names