Managing directories and paths

Input/Output and Streams in Java

Alex Liu

Software Developer Engineer

Key concept

  • Directories organize files and data
  • Paths specify the location of files and directories
  • File class can represent either a file or a directory
    • The actual resource created depends on the method called (mkdir() for directories and createNewFile() for files)

Computer monitor with several directories icons

Input/Output and Streams in Java

Creating directories

  • Import the File class
    import java.io.File;
    
  • Creates a File object representing the directory
    File newDirectory = new File("myDirectory");
    
  • Use .mkdir() creates the actual directory on the file system
    boolean created = newDirectory.mkdir();
    
  • Returns true if the directory is created successfully
  • Returns false if the directory already exists or cannot be created
Input/Output and Streams in Java

Listing files in a directory

  • Use .listFiles() to list files in directory

$$

// Creates a `File` object representing the directory `myDirectory`
File dir = new File("myDirectory");
//Retrieves an `array` of `File` objects representing the contents of `myDirectory`
File[] files = dir.listFiles();
  • Returns an array of File objects if the directory exists
  • Returns null if the directory does not exist
Input/Output and Streams in Java

Retrieving a file's relative Path

  • Relative Path: location of a file/directory in relation to the current working directory
// Creates a `File` object for `sample.txt` inside `myDirectory`
File file = new File("myDirectory/sample.txt");
// Retrieves the relative path of the file as a String
String path = file.getPath();
System.out.println(path);
  • We assume myDirectory already exists; otherwise, file creation or writing will fail

  • Output:

    myDirectory/sample.txt
    
Input/Output and Streams in Java

Working with absolute paths

  • Absolute Path: the full path from the root of the file system

$$

// Creates a `File` object for `sample.txt` inside `myDirectory`
File file = new File("myDirectory/sample.txt");
// Retrieves the absolute path of the file as a String
String absPath = file.getAbsolutePath();
System.out.println(absPath);
  • Output:
/user/home/myDirectory/sample.txt
Input/Output and Streams in Java

Let's practice!

Input/Output and Streams in Java

Preparing Video For Download...