I/O

io1FileBasics

Path
pkg9io/io1FileBasics.java
Package
pkg9io
Study order
1
Run
Single-file source launch
Command
java pkg9io/io1FileBasics.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg9io/io1FileBasics.java
1package pkg9io;2 3import java.io.File;4import java.io.IOException;5 6/*7 * io1FileBasics.java8 * ------------------9 * The legacy java.io.File API: representing paths, files, and directories.10 *11 * DEFINITION:12 *   A File object is an abstract handle to a path on disk. Creating a File13 *   does NOT touch the disk — you must call methods (createNewFile, mkdirs,14 *   delete) to actually act on the filesystem.15 *16 * KEY POINTS:17 *   - File works for both files and directories (it is just a path).18 *   - Use File.separator for portable paths; prefer java.nio (io4) for new code.19 *   - exists(), isFile(), isDirectory(), length(), canRead() inspect a path.20 *   - Clean up temp resources so the demo is repeatable.21 */22public class io1FileBasics {23 24    public static void main(String[] args) throws IOException {25        File dir = new File("io_demo_dir");26        File file = new File(dir, "notes.txt");   // nested path: io_demo_dir/notes.txt27 28        System.out.println("Path string      : " + file.getPath());29        System.out.println("File.separator   : '" + File.separator + "'");30 31        // Create directory + file on disk32        boolean dirMade  = dir.mkdirs();          // creates parent dirs too33        boolean fileMade = file.createNewFile();  // creates empty file34        System.out.println("\nDirectory created: " + dirMade);35        System.out.println("File created     : " + fileMade);36 37        // Inspect the path now that it exists38        System.out.println("\nexists()         : " + file.exists());39        System.out.println("isFile()         : " + file.isFile());40        System.out.println("isDirectory()    : " + file.isDirectory());41        System.out.println("length() bytes   : " + file.length());42        System.out.println("absolute path    : " + file.getAbsolutePath());43 44        // List directory contents45        System.out.println("\nContents of " + dir.getName() + ":");46        File[] children = dir.listFiles();47        if (children != null) for (File c : children) System.out.println("  - " + c.getName());48 49        // Cleanup so the demo can be re-run50        file.delete();51        dir.delete();52        System.out.println("\nCleaned up. exists()? " + file.exists());53    }54}