|
| 1 | +--- |
| 2 | +sidebar_position: 51 |
| 3 | +title: A.51. File, Path, Directory |
| 4 | +sidebar_label: A.51. File, Path, Directory |
| 5 | +--- |
| 6 | + |
| 7 | +Pada chapter ini kita akan belajar tentang beberapa API milik Rust yang disediakan untuk manajemen path dan file system. |
| 8 | + |
| 9 | +## A.51.1. File path (`std::path::Path`) |
| 10 | + |
| 11 | +`"/home/novalagung/Desktop/my text.txt"` adalah salah satu contoh file path. Di Rust, file path bisa direpresentasikan sebagai string (seperti yang sudah dicontohkan), atau menggunakan tipe data `Path`. |
| 12 | + |
| 13 | +Tipe data `Path` tersedia dalam module `std::path`. Cara penggunaannya cukup mudah, sebagai contoh, beberapa filepath berikut menghasilkan path yang sama: |
| 14 | + |
| 15 | +```rust |
| 16 | +let filepath_1 = "/home/novalagung/Desktop/my text.txt"; |
| 17 | +let filepath_2 = Path::new("/home/novalagung/Desktop/my text.txt"); |
| 18 | +let filepath_3 = Path::new("/home/novalagung/Desktop").join("my text.txt"); |
| 19 | +let filepath_4 = Path::new("/home/novalagung").join("Desktop").join("my text.txt"); |
| 20 | +let filepath_5 = Path::new("/home").join("novalagung/Desktop/my text.txt"); |
| 21 | +``` |
| 22 | + |
| 23 | +## A.52.2. Method filepath |
| 24 | + |
| 25 | +### ◉ Associated function `Path::new()` |
| 26 | + |
| 27 | +Digunakan untuk membuat object `Path` dari suatu string. Contoh penerapan: |
| 28 | + |
| 29 | +```rust |
| 30 | +Path::new("/home/novalagung/Desktop/my text.txt"); |
| 31 | +``` |
| 32 | + |
| 33 | +### ◉ Method `join()` |
| 34 | + |
| 35 | +Digunakan untuk menggabungkan segment filepath. Contoh penerapan: |
| 36 | + |
| 37 | +```rust |
| 38 | +Path::new("/home/novalagung").join("Desktop").join("my text.txt"); |
| 39 | +``` |
| 40 | + |
| 41 | +Hasil dari operasi di atas adalah path: |
| 42 | + |
| 43 | +``` |
| 44 | +/home/novalagung/Desktop/my text.txt |
| 45 | +``` |
| 46 | + |
| 47 | +### ◉ Method `exists()` |
| 48 | + |
| 49 | +Digunakan untuk mengecek apakah suatu filepath ada atau tidak. |
| 50 | + |
| 51 | +```rust |
| 52 | +if Path::new(path).exists() { |
| 53 | + // path exists |
| 54 | +} |
| 55 | +``` |
| 56 | + |
| 57 | +### ◉ Method `is_file()` & `is_dir()` |
| 58 | + |
| 59 | +Method `is_file()` digunakan untuk mengecek apakah suatu filepath berisi file. |
| 60 | + |
| 61 | +```rust |
| 62 | +if Path::new(path).is_file() { |
| 63 | + // path is a file |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +Sedangkan method `is_dir()` digunakan untuk mengecek apakah suatu filepath adalah folder/directory. |
| 68 | + |
| 69 | +```rust |
| 70 | +if Path::new(path).is_dir() { |
| 71 | + // path contains directory |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +### ◉ Method `is_absolute()` & `is_relative()` |
| 76 | + |
| 77 | +Method `is_absolute()` digunakan untuk mengecek apakah suatu filepath adalah *absolute path*. |
| 78 | + |
| 79 | +```rust |
| 80 | +if Path::new(path).is_absolute() { |
| 81 | + // path is an absolute path |
| 82 | +} |
| 83 | +``` |
| 84 | + |
| 85 | +Sedangkan method `is_relative()` digunakan untuk mengecek apakah suatu filepath adalah *relative path*. |
| 86 | + |
| 87 | +```rust |
| 88 | +if Path::new(path).is_relative() { |
| 89 | + // path is a relative path |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | +## A.52.3. Module `std::fs` (file system) |
| 94 | + |
| 95 | +`std::fs` merupakan module yang disediakan Rust untuk pengolahan file system. Didalamnya berisinya banyak sekali fungsi untuk keperluan seperti pembuatan file, modifikasi konten file, dan lainnya. |
| 96 | + |
| 97 | +Sebagai contoh, untuk membuat suatu directory bisa menggunakan `fs::create_dir`. Isi argument pemanggilan fungsi dengan path dalam bentuk string (atau `std::path::Path` juga boleh). |
| 98 | + |
| 99 | +```rust |
| 100 | +let path = "./files"; |
| 101 | +let res = fs::create_dir(path); |
| 102 | +``` |
| 103 | + |
| 104 | +Fungsi `fs::create_dir` mengembalikan value bertipe `Result<(), Error>`. Gunakan pattern matching `match` untuk mengecek hasil operasi apakah sukses atau tidak. |
| 105 | + |
| 106 | +```rust |
| 107 | +match fs::create_dir("./files") { |
| 108 | + Err(err) => { |
| 109 | + println!("error on creating directory! {}", err); |
| 110 | + return |
| 111 | + }, |
| 112 | + _ => {}, |
| 113 | +} |
| 114 | +``` |
| 115 | + |
| 116 | +> - Lebih detailnya mengenai tipe data `Result` dibahas pada chapter [Tipe Data → Result](/basic/result-type). |
| 117 | +> - Lebih detailnya mengenai pattern matching dibahas pada chapter [Pattern Matching](/basic/pattern-matching). |
| 118 | +
|
| 119 | +## A.52.4. Manajemen file system |
| 120 | + |
| 121 | +### ◉ Pembuatan folder (`fs::create_dir`) |
| 122 | + |
| 123 | +Fungsi `fs::create_dir` digunakan untuk membuat folder. Contoh penerapannya sudah dibahas di sesi [A.52.3. Module std::fs (file system)](/file-path-directory#a523-module-stdfs-file-system) di atas. |
| 124 | + |
| 125 | +### ◉ Menulis konten file (`fs::write`) |
| 126 | + |
| 127 | +Fungsi `fs::write` digunakan untuk membuat folder. Contoh penerapan: |
| 128 | + |
| 129 | +```rust |
| 130 | +let path = Path::new("./files").join("target.txt"); |
| 131 | +let content = "hello rust!"; |
| 132 | +let res = fs::write(path, content); |
| 133 | + |
| 134 | +match res { |
| 135 | + Err(err) => { |
| 136 | + println!("error on writing file {}! {}", path.to_str().unwrap_or_default(), err); |
| 137 | + return |
| 138 | + }, |
| 139 | + _ => {}, |
| 140 | +} |
| 141 | +``` |
| 142 | + |
| 143 | +Fungsi `fs::write` melakukan penulisan konten pada variabel `content` ke path `path`. Mode penulisannya adalah *overwrite* (bukan *append*), yang artinya konten lama pada filepath akan di-*replace* total dengan konten baru. |
| 144 | + |
| 145 | +Jika file tidak ada pada `path` tujuan, maka otomatis dibuatkan file baru. Namun jika folder/directory dimana file akan dibuat/ditulis tidak ada, maka muncul error. |
| 146 | + |
| 147 | +### ◉ Menghapus file (`fs::remove_file`) |
| 148 | + |
| 149 | +Fungsi `fs::remove_file` digunakan untuk menghapus file pada suatu path. Contoh penerapan: |
| 150 | + |
| 151 | +```rust |
| 152 | +let path = Path::new("./files").join("target.txt"); |
| 153 | +let res = fs::remove_file(path); |
| 154 | + |
| 155 | +match res { |
| 156 | + Err(err) => { |
| 157 | + println!("error on deleting file {}! {}", path.to_str().unwrap_or_default(), err); |
| 158 | + return |
| 159 | + }, |
| 160 | + _ => {}, |
| 161 | +} |
| 162 | +``` |
| 163 | + |
| 164 | +### ◉ Menghapus folder (`fs::remove_dir`) |
| 165 | + |
| 166 | +Fungsi `fs::remove_dir` digunakan untuk menghapus folder/directory. Contoh penerapan: |
| 167 | + |
| 168 | +```rust |
| 169 | +let path = Path::new("./files"); |
| 170 | +let res = fs::remove_dir(path); |
| 171 | + |
| 172 | +match res { |
| 173 | + Err(err) => { |
| 174 | + println!("error on deleting directory {}! {}", path.to_str().unwrap_or_default(), err); |
| 175 | + return |
| 176 | + }, |
| 177 | + _ => {}, |
| 178 | +} |
| 179 | +``` |
| 180 | + |
| 181 | +### ◉ List items dalam folder |
| 182 | + |
| 183 | +Fungsi `fs::read_dir` digunakan untuk menampilkan list items suatu folder (baik subfolder ataupun file). Fungsi ini mengmbalikan nilai bertipe `Result<ReadDir, Error>`, untuk mengakses list items bisa menggunakan teknik pattern matching, atau boleh juga langsung di `unwrap()` (dengan resiko program bisa panic ketika ada error). |
| 184 | + |
| 185 | +```rust |
| 186 | +let path = Path::new("D:\\Labs\\Adam Studio\\Ebook\\dasarpemrogramanrust\\file_path_directory_1"); |
| 187 | +let paths = fs::read_dir(path).unwrap(); |
| 188 | + |
| 189 | +for path in paths { |
| 190 | + let item = path.unwrap(); |
| 191 | + println!("file name: {:?}, file path: {:?}", item.file_name(), item.path().display()) |
| 192 | +} |
| 193 | +``` |
| 194 | + |
| 195 | +Pada contoh di atas, penulis menggunakan testing path yang isinya 4 buah item: |
| 196 | + |
| 197 | + |
| 198 | + |
| 199 | +Output program bisa dilihat pada gambar berikut: |
| 200 | + |
| 201 | + |
| 202 | + |
| 203 | +Tipe data variabel `paths` di atas adalah `ReadDir` yang merupakan tipe data iterator. Jika digunakan pada keyword `for`, maka variabel element perulangan `path` akan bertipe data `Result<DirEntry, Error>`. Dari tipe ini kita bisa mengakses file name maupun file path. |
| 204 | + |
| 205 | +--- |
| 206 | + |
| 207 | +## Catatan chapter 📑 |
| 208 | + |
| 209 | +### ◉ Source code praktik |
| 210 | + |
| 211 | +<pre> |
| 212 | + <a href="https://github.com/novalagung/dasarpemrogramanrust-example/tree/master/file_path_directory"> |
| 213 | + github.com/novalagung/dasarpemrogramanrust-example/../file_path_directory |
| 214 | + </a> |
| 215 | +</pre> |
| 216 | + |
| 217 | +### ◉ Work in progress |
| 218 | + |
| 219 | +- Pembahasan tentang append content file (https://stackoverflow.com/questions/30684624/what-is-the-best-variant-for-appending-a-new-line-in-a-text-file) |
| 220 | + |
| 221 | +### ◉ Chapter relevan lainnya |
| 222 | + |
| 223 | +- [Tipe Data → Result](/basic/result-type) |
| 224 | +- [Pattern Matching](/basic/pattern-matching) |
| 225 | + |
| 226 | +### ◉ Referensi |
| 227 | + |
| 228 | +- https://doc.rust-lang.org/std/path/struct.Path.html |
| 229 | +- https://doc.rust-lang.org/rust-by-example/std_misc/path.html |
| 230 | +- https://doc.rust-lang.org/rust-by-example/std_misc/fs.html |
| 231 | + |
| 232 | +--- |
0 commit comments