Správa adresářů a cest

Input/Output and Streams in Java

Alex Liu

Software Developer Engineer

Klíčové pojmy

  • Adresáře organizují soubory a data
  • Cesty určují umístění souborů a adresářů
  • Třída File může představovat soubor i adresář
    • Skutečný zdroj závisí na volané metodě (mkdir() pro adresáře, createNewFile() pro soubory)

Monitor počítače s ikonami adresářů

Input/Output and Streams in Java

Vytváření adresářů

  • Import třídy File
    import java.io.File;
    
  • Vytvoří objekt File reprezentující adresář
    File newDirectory = new File("myDirectory");
    
  • .mkdir() vytvoří skutečný adresář v souborovém systému
    boolean created = newDirectory.mkdir();
    
  • Vrátí true, pokud byl adresář úspěšně vytvořen
  • Vrátí false, pokud adresář již existuje nebo jej nelze vytvořit
Input/Output and Streams in Java

Výpis souborů v adresáři

  • .listFiles() vypíše soubory v adresáři

$$

// 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();
  • Vrátí pole (array) objektů File, pokud adresář existuje
  • Vrátí null, pokud adresář neexistuje
Input/Output and Streams in Java

Získání relativní cesty souboru

  • Relativní cesta: umístění souboru/adresáře vůči aktuálnímu pracovnímu adresáři
// 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);
  • Předpokládáme, že myDirectory již existuje; jinak vytvoření nebo zápis souboru selže

  • Výstup:

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

Práce s absolutními cestami

  • Absolutní cesta: úplná cesta od kořene souborového systému

$$

// 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);
  • Výstup:
/user/home/myDirectory/sample.txt
Input/Output and Streams in Java

Pojďme si procvičit!

Input/Output and Streams in Java

Preparing Video For Download...