Thuta Learning
Java
AdvancedProgrammingအခြေခံ

File I/O with Path & Files

Javaသင်ခန်းစာ 2630 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Path (တည်နေရာ) နဲ့ Files (လုပ်ဆောင်ချက်) ရဲ့ တာဝန် ကွာခြားချက်ကို ရှင်းပြနိုင်ဖို့
  • Files.writeString, readString, readAllLines နဲ့ APPEND option ကို charset ပြတ်ပြတ်သားသားနဲ့ သုံးနိုင်ဖို့
  • File ကြီးတွေကို BufferedReader ဒါမှမဟုတ် Files.lines နဲ့ try-with-resources ထဲမှာ line တစ်ကြောင်းချင်း ဖတ်နိုင်ဖို့
  • NoSuchFileException လို IOException subclass တွေကို ကိုင်တွယ်ပြီး temp file တွေကို ရှင်းလင်းနိုင်ဖို့
  • resolve() နဲ့ normalize() သုံးပြီး ခွင့်ပြုထားတဲ့ folder အပြင်ဘက် ထွက်မသွားအောင် စစ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Path ကို အိမ်လိပ်စာ တစ်ခုလို မြင်ကြည့်ပါ — "reports/2026/summary.txt" ဆိုတာ ဘယ်နေရာမှာ ရှိလဲ ပြောရုံပါပဲ၊ အဲဒီ အိမ်တကယ် ရှိမရှိကိုတောင် မစစ်ပါဘူး။ Files ကတော့ စာပို့သမားပါ — အဲဒီ လိပ်စာကို တကယ်သွားပြီး စာရေးတာ၊ ဖတ်တာ၊ ဖျက်တာတွေ လုပ်ပေးပါတယ်။

စာပို့သမားရဲ့ ခရီးက မှားနိုင်ပါတယ် — file မရှိတာ၊ folder မရှိတာ၊ permission မရှိတာ၊ disk ပြည့်နေတာတွေ ဖြစ်နိုင်လို့ Files method အများစုက IOException ပစ်ပါတယ်။ ဒါကြောင့် file I/O code တိုင်းမှာ "မှားခဲ့ရင် ဘာလုပ်မလဲ" ဆိုတာကို ကြိုစဉ်းစားထားရပါတယ်။

Problem → Why → Solution

ပြဿနာ: ကိုယ့်စက်မှာ အလုပ်ဖြစ်ပြီး server မှာ ပျက်တဲ့ file code

အောက်က code မှာ ပြဿနာ သုံးခု ပုန်းနေပါတယ်။ ပထမ — charset မပေးထားတဲ့ getBytes() နဲ့ new String() က platform ရဲ့ default charset ကို သုံးပါတယ်၊ Java 18 မတိုင်ခင် JDK တွေမှာ Windows စက်နဲ့ Linux server ပေါ်မှာ ကွဲပြားနိုင်လို့ "café" လို စာလုံးတွေ ပျက်သွားနိုင်ပါတယ်။ ဒုတိယ — user ပေးတဲ့ name ကို စစ်မထားလို့ "../../etc/passwd" လို တန်ဖိုးနဲ့ uploads folder အပြင်ဘက်က file ကို ဖတ်လို့ ရသွားပါတယ်။

တတိယ — reports folder မရှိသေးရင် write() က NoSuchFileException ပစ်ပြီး program ရပ်သွားပါတယ်။

Main.java
import java.nio.file.*;

public class Main {
  public static void main(String[] args) throws Exception {
    String name = args[0];                        // e.g. "../../etc/passwd"
    Path upload = Path.of("uploads", name);       // never validated
    String text = new String(Files.readAllBytes(upload)); // platform charset
    Files.write(Path.of("reports/out.txt"), text.getBytes()); // folder may not exist
  }
}

ဘာကြောင့် ဒီ bug တွေ စောစောမပေါ်တာလဲ

Developer ရဲ့ စက်မှာ folder တွေ ရှိပြီးသား၊ charset တူနေပြီး ကိုယ်တိုင် ရိုက်ထည့်တဲ့ file နာမည်တွေက ရိုးရိုးပဲ ဖြစ်နေလို့ပါ။ ဖြေရှင်းချက်က charset ကို StandardCharsets.UTF_8 လို့ အမြဲ ပြတ်ပြတ်သားသား ပေးတာ၊ parent folder ကို Files.createDirectories() နဲ့ ဖန်တီးတာ၊ user input ကနေ လာတဲ့ path ကို normalize() လုပ်ပြီး ခွင့်ပြုထားတဲ့ root အောက်မှာ ရှိမရှိ စစ်တာ ဖြစ်ပါတယ်။

Core concept: Path က လိပ်စာ၊ Files က လုပ်ဆောင်ချက်

Path object ကို Path.of("data", "notes.txt") လို ဖန်တီးပါတယ်။ ဒါက string ပေါင်းတာထက် ပိုကောင်းပါတယ်၊ operating system အလိုက် separator (/ ဒါမှမဟုတ် \) ကို Java က ကိုင်တွယ်ပေးလို့ပါ။ resolve() က folder path တစ်ခုရဲ့ နောက်မှာ အစိတ်အပိုင်း ထပ်ဆက်ပေးပြီး getFileName(), getParent() က path ကို ခွဲပေးပါတယ်။ normalize() ကတော့ "." နဲ့ ".." တွေကို ဖယ်ရှားပေးပါတယ်။ ဒီ method တွေ တစ်ခုမှ disk ကို မထိပါဘူး — Path က immutable value object တစ်ခုပဲ ဖြစ်ပါတယ်။

Disk ကို တကယ် ထိတဲ့ အလုပ်တွေကို Files class ရဲ့ static method တွေက လုပ်ပါတယ်။ File သေးသေးလေးတွေအတွက် Files.writeString() နဲ့ Files.readString() (Java 11 ကစပြီး ပါ) က တစ်ကြောင်းတည်းနဲ့ ပြီးပါတယ်။ Files.readAllLines() က line တွေကို List<String> အဖြစ် ပြန်ပေးပါတယ်။ ဒီ method သုံးခုလုံးက file တစ်ခုလုံးကို memory ထဲ ထည့်လို့ megabyte ရာချီတဲ့ log file တွေအတွက်တော့ Files.newBufferedReader() ဒါမှမဟုတ် Files.lines() နဲ့ line တစ်ကြောင်းချင်း ဖတ်ရပါမယ်။

Write method တွေရဲ့ default အပြုအမူကို သိထားရပါမယ်။ Option မပေးရင် writeString() က file မရှိရင် ဖန်တီးပြီး ရှိရင် အရင် content ကို ဖျက်ပြီး အစားထိုးရေးပါတယ် (CREATE, TRUNCATE_EXISTING, WRITE)။ နောက်က ဆက်ထည့်ချင်ရင် StandardOpenOption.APPEND ကို ပေးရပြီး file မရှိသေးတဲ့ case အတွက် CREATE ပါ တွဲပေးရပါတယ်။ Charset အတွက် Files method တွေက charset မပေးရင် UTF-8 ကို သုံးပေမယ့် StandardCharsets.UTF_8 ကို ပြတ်ပြတ်သားသား ရေးထားတာက code ဖတ်တဲ့သူကို ရည်ရွယ်ချက် ရှင်းရှင်းပြပါတယ်။

Files method အများစုက checked IOException ပစ်ပါတယ်။ အသုံးများတဲ့ subclass တွေကတော့ file မရှိရင် NoSuchFileException၊ ဖန်တီးမယ့် file ရှိပြီးသားဆိုရင် FileAlreadyExistsException၊ ဗလာမဟုတ်တဲ့ folder ကို ဖျက်ရင် DirectoryNotEmptyException တို့ပါ။ Specific subclass ကို ဖမ်းခြင်းအားဖြင့် "file မရှိသေးလို့ default သုံးမယ်" နဲ့ "disk ပျက်နေလို့ ရပ်ရမယ်" ကို ခွဲခြားပြီး တုံ့ပြန်နိုင်ပါတယ်။ Stream ဒါမှမဟုတ် reader ဖွင့်တဲ့ method တွေကို try-with-resources နဲ့ အမြဲ ပိတ်ရပါမယ်၊ မပိတ်ရင် operating system ရဲ့ file handle တွေ ကုန်သွားနိုင်ပါတယ်။

မှတ်ထားရမယ့် ပုံစံ: လိပ်စာ၊ ခရီး၊ ရှင်းလင်းရေး
  1. Path နဲ့ လိပ်စာ တည်ဆောက်
  2. User input ပါရင် root အောက်မှာလား စစ်
  3. Files နဲ့ UTF-8 ရေး/ဖတ်
  4. IOException ကို ကိုင်တွယ်
  5. Resource နဲ့ temp file ကို ရှင်း

Path ဖန်တီးတာ ဘယ်တော့မှ မမှားပါဘူး၊ မှားနိုင်တာက Files နဲ့ disk ကို ထိတဲ့ အချိန်ပါ။

အထွေထွေ ပုံစံ

java
Path file = Path.of("folder", "name.txt");
Files.createDirectories(file.getParent());
Files.writeString(file, text, StandardCharsets.UTF_8);
Files.writeString(file, more, StandardCharsets.UTF_8,
    StandardOpenOption.CREATE, StandardOpenOption.APPEND);
String all = Files.readString(file, StandardCharsets.UTF_8);
try (BufferedReader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
  String line;
  while ((line = in.readLine()) != null) { handle(line); }
}

Path.of() နဲ့ လိပ်စာ ဆောက်ပြီး createDirectories() နဲ့ parent folder ရှိအောင် လုပ်ပါတယ်။ writeString() က content ကို အစားထိုးပြီး APPEND နဲ့ဆိုရင် နောက်က ဆက်ထည့်ပါတယ်။ File သေးရင် readString()၊ ကြီးရင် BufferedReader နဲ့ line တစ်ကြောင်းချင်း ဖတ်ပြီး reader ကို try-with-resources နဲ့ ပိတ်ပါတယ်။

Example: temp file မှာ ရေးပြီး ပြန်ဖတ်ခြင်း

ဒီ example က OS ရဲ့ temp folder ထဲမှာ နာမည်မတူတဲ့ file အသစ်တစ်ခု ဖန်တီးပြီး UTF-8 နဲ့ ရေး၊ ပြန်ဖတ်ပြီး finally ထဲမှာ ဖျက်ပါတယ်။ Temp file သုံးတာက ကိုယ့် project folder ထဲက file တွေကို မတော်တဆ overwrite မလုပ်မိအောင် ကာကွယ်ပေးပါတယ်။

java
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

class Main {
    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("java-notes-", ".txt");
        try {
            Files.writeString(file, "Safe Java I/O", StandardCharsets.UTF_8);
            System.out.println(Files.readString(file, StandardCharsets.UTF_8));
        } finally {
            Files.deleteIfExists(file);
        }
    }
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Line 6public static void main(String[] args) throws Exception {

    Files method တွေက checked IOException ပစ်လို့ main() မှာ throws ကြေညာထားပါတယ်။ Demo အတွက် အဆင်ပြေပေမယ့် real code မှာ throws IOException လို ပိုတိကျတဲ့ type ကို ရေးတာ ပိုကောင်းပါတယ်။

  2. Line 7Path file = Files.createTempFile("java-notes-", ".txt");

    Temp folder ထဲမှာ java-notes- နဲ့ စပြီး .txt နဲ့ ဆုံးတဲ့ file အလွတ်တစ်ခုကို ဖန်တီးပါတယ်။ ကြားထဲက random အစိတ်အပိုင်းကြောင့် run တိုင်း နာမည်မတူတဲ့ file ရပါတယ်။

  3. Line 9Files.writeString(file, "Safe Java I/O", StandardCharsets.UTF_8);

    String ကို UTF-8 byte တွေအဖြစ် ပြောင်းပြီး ရေးပါတယ်။ Option မပေးထားလို့ file ထဲမှာ ရှိပြီးသား content ရှိရင် အစားထိုးပါတယ်။

  4. Line 10System.out.println(Files.readString(file, StandardCharsets.UTF_8));

    ရေးခဲ့တဲ့ charset အတူတူနဲ့ ပြန်ဖတ်ပါတယ်။ ရေးတဲ့ charset နဲ့ ဖတ်တဲ့ charset မတူရင် စာလုံးတွေ ပျက်တတ်ပါတယ်။

  5. Lines 11-12Files.deleteIfExists(file);

    finally ထဲမှာ ထားလို့ ရေးတာ ဒါမှမဟုတ် ဖတ်တာ မှားခဲ့ရင်တောင် temp file ကို ဖျက်ပါတယ်။ deleteIfExists() က file မရှိရင် exception မပစ်ဘဲ false ပြန်ပါတယ်။

You should see
Safe Java I/O

Append နဲ့ line တစ်ကြောင်းချင်း ဖတ်ခြင်း

Log file လို ကြီးလာနိုင်တဲ့ file တွေမှာ BufferedWriter နဲ့ ရေးပြီး BufferedReader နဲ့ တစ်ကြောင်းချင်း ဖတ်ပါတယ်။ အောက်က program က temp folder တစ်ခုထဲမှာ log file ရေးပြီး WARN line တွေကို ရေတွက်ပါတယ်။ Reader နဲ့ writer နှစ်ခုလုံး try-with-resources ထဲမှာ ရှိလို့ block ပြီးတာနဲ့ ပိတ်သွားပြီး buffer ထဲက data တွေ disk ပေါ် ရောက်သွားပါတယ်။

Main.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class Main {
  public static void main(String[] args) throws IOException {
    Path dir = Files.createTempDirectory("io-demo-");
    Path log = dir.resolve("app.log");
    try {
      try (BufferedWriter out = Files.newBufferedWriter(log, StandardCharsets.UTF_8)) {
        out.write("INFO started");
        out.newLine();
        out.write("WARN disk 91%");
        out.newLine();
      }
      Files.writeString(log, "INFO stopped\n", StandardCharsets.UTF_8,
          StandardOpenOption.APPEND);

      int warnings = 0;
      try (BufferedReader in = Files.newBufferedReader(log, StandardCharsets.UTF_8)) {
        String line;
        while ((line = in.readLine()) != null) {
          if (line.startsWith("WARN")) warnings++;
        }
      }
      int total = Files.readAllLines(log, StandardCharsets.UTF_8).size();
      System.out.println("Lines: " + total);
      System.out.println("Warnings: " + warnings);
      System.out.println("File name: " + log.getFileName());
    } finally {
      Files.deleteIfExists(log);
      Files.deleteIfExists(dir);
    }
  }
}

Output က Lines: 3, Warnings: 1, File name: app.log ပါ။ Absolute temp path ကို print မထုတ်ဘဲ getFileName() နဲ့ နာမည်ပဲ ပြထားတာကို သတိထားပါ — temp path က စက်တစ်လုံးချင်း မတူလို့ပါ။ newLine() က platform ရဲ့ line separator ကို ရေးတာကိုလည်း မှတ်ထားပါ၊ Windows မှာ \r\n ဖြစ်ပြီး Linux မှာ \n ဖြစ်ပါတယ်။

မရှိတဲ့ file နဲ့ folder တွေကို ကိုင်တွယ်ခြင်း

File မရှိတာက ပုံမှန်ဖြစ်နိုင်တဲ့ case တစ်ခုပါ (ဥပမာ ပထမဆုံး run တဲ့အခါ settings file မရှိသေးတာ)။ NoSuchFileException ကို သီးသန့် ဖမ်းပြီး default ကို သုံးနိုင်ပါတယ်။ Nested folder ထဲ ရေးမယ်ဆိုရင် Files.createDirectories() က လိုအပ်တဲ့ parent folder အားလုံးကို ဖန်တီးပေးပြီး ရှိပြီးသားဆိုရင် error မပေးပါဘူး။

Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) throws IOException {
    Path dir = Files.createTempDirectory("missing-demo-");
    try {
      Path settings = dir.resolve("settings.txt");
      System.out.println("Exists: " + Files.exists(settings));
      try {
        Files.readString(settings);
      } catch (NoSuchFileException e) {
        System.out.println("Not found: " + Path.of(e.getFile()).getFileName());
      }
      Path nested = dir.resolve("reports/2026/summary.txt");
      Files.createDirectories(nested.getParent());
      Files.writeString(nested, "ok");
      System.out.println("Nested written: " + Files.readString(nested));
      System.out.println("Parent folder: " + nested.getParent().getFileName());
      Files.delete(nested);
      Files.delete(nested.getParent());
      Files.delete(nested.getParent().getParent());
    } finally {
      Files.deleteIfExists(dir);
    }
  }
}

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Backend application တွေမှာ file I/O ကို CSV report ထုတ်တာ၊ user upload လုပ်တဲ့ file ကို disk ပေါ် သိမ်းတာ၊ config file ဖတ်တာ၊ batch job တွေက data file တွေကို process လုပ်တာတွေမှာ သုံးပါတယ်။ Upload feature မှာ user ပေးတဲ့ file နာမည်ကို ဘယ်တော့မှ တိုက်ရိုက် မယုံပါဘူး — server က UUID လို ကိုယ်ပိုင် နာမည်ပေးတာ ဒါမှမဟုတ် resolve().normalize() ပြီးမှ startsWith(root) နဲ့ စစ်တာ လုပ်ပါတယ်၊ "../" သုံးတဲ့ path traversal attack က အဖြစ်များတဲ့ security bug တစ်ခုမို့ပါ။

File တစ်ခုကို update လုပ်တဲ့အခါ တိုက်ရိုက် overwrite မလုပ်ဘဲ ဘေးမှာ temp file အသစ် ရေးပြီး Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) နဲ့ အစားထိုးတာက အသုံးများတဲ့ pattern ပါ။ ရေးနေတုန်း process ရပ်သွားရင် file ဟောင်းက မပျက်ဘဲ ကျန်နေပါတယ်။ Unit test တွေမှာလည်း ဒီ lesson ထဲကလို createTempDirectory() နဲ့ test တစ်ခုချင်းစီအတွက် သီးသန့် folder ဖန်တီးပြီး test ပြီးရင် ဖျက်ပါတယ် — JUnit 5 ရဲ့ @TempDir က ဒီအလုပ်ကို အလိုအလျောက် လုပ်ပေးပါတယ်။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. APPEND ကို မေ့ပြီး data ဟောင်းကို ဖျက်မိတာ

Note အသစ်တစ်ကြောင်း ထည့်ဖို့ Files.writeString(file, note) ကို ခေါ်လိုက်ရင် default TRUNCATE_EXISTING ကြောင့် file ထဲက ရှိပြီးသား note တွေ အားလုံး ပျောက်သွားပါတယ်။ ဆက်ထည့်ချင်ရင် StandardOpenOption.CREATE, StandardOpenOption.APPEND ကို ပေးပါ။

2. Files.lines() ကို မပိတ်တာ

Files.lines() နဲ့ Files.walk() က ဖွင့်ထားတဲ့ file handle ကို ကိုင်ထားတဲ့ Stream ပြန်ပေးပါတယ်။ try-with-resources မသုံးရင် handle တွေ ယိုစိမ့်ပြီး Windows မှာ အဲဒီ file ကို ဖျက်လို့ မရတော့တာ ဒါမှမဟုတ် server မှာ "Too many open files" error တက်တာ ဖြစ်တတ်ပါတယ်။

3. normalize() မလုပ်ဘဲ startsWith() နဲ့ စစ်တာ

root.resolve("../secret.txt") က ".." ကို ဆက်ထိန်းထားလို့ startsWith(root) က true ပြန်ပါတယ် — စစ်ဆေးမှုက ဘာမှ မကာကွယ်ပါဘူး။ startsWith() မစစ်ခင် normalize() ကို အရင်ခေါ်ပါ။

4. Absolute temp path ကို log ဒါမှမဟုတ် output မှာ ထုတ်တာ

Temp path က စက်တစ်လုံးချင်း ကွဲပြားပြီး user နာမည်လို အချက်အလက်တွေ ပါနိုင်ပါတယ်။ getFileName() ဒါမှမဟုတ် relativize() နဲ့ ပြပါ။

Mini challenge

Mini challenge: ဘေးကင်းတဲ့ notes store

Temp folder တစ်ခုကို notes root အဖြစ် သုံးပြီး notes.txt ထဲ note တွေ append လုပ်၊ ပြန်ဖတ်ပြီး နံပါတ်တပ် print ထုတ်ပါ။ Root အပြင်ဘက် ထွက်တဲ့ file နာမည်ကို ပိတ်ပင်ပြီး မရှိတဲ့ file ကို ဖတ်တဲ့ case ကို ကိုင်တွယ်ပါ။ အဆုံးမှာ folder တစ်ခုလုံးကို ဖျက်ပါ။

  • safeResolve(root, name) က resolve() + normalize() လုပ်ပြီး root အပြင်ဘက်ဆိုရင် IllegalArgumentException ပစ်ရမယ်
  • addNote() က UTF-8, CREATE နဲ့ APPEND သုံးပြီး note တစ်ခုကို line တစ်ကြောင်းအဖြစ် ထည့်ရမယ်
  • Note အရေအတွက်နဲ့ "1. buy milk" ပုံစံ line တွေကို print ထုတ်ရမယ်
  • "../secret.txt" ကို ပိတ်ပင်ပြီး မရှိတဲ့ archive.txt အတွက် NoSuchFileException ကို ဖမ်းရမယ်
  • finally ထဲမှာ Files.walk() ကို try-with-resources နဲ့ သုံးပြီး folder တစ်ခုလုံး ဖျက်ရမယ်၊ absolute path မထုတ်ရ
Main.java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class Main {
  static Path safeResolve(Path root, String name) {
    // TODO: resolve + normalize, then reject anything outside root
    return root;
  }

  static void addNote(Path file, String note) throws IOException {
    // TODO: append note plus a newline (UTF-8, CREATE, APPEND)
  }

  static void deleteTree(Path root) throws IOException {
    // TODO: walk the tree (close the stream!) and delete deepest paths first
  }

  public static void main(String[] args) throws IOException {
    Path root = Files.createTempDirectory("notes-").toAbsolutePath().normalize();
    try {
      // TODO: add three notes, read them back, print them numbered
      // TODO: try "../secret.txt" and a missing "archive.txt"
    } finally {
      deleteTree(root);
    }
  }
}

ရလဒ်: Program က ဒီ output ကို ထုတ်ရပါမယ်: Notes: 3 1. buy milk 2. call Aye 3. pay rent Blocked: outside the notes folder: ../secret.txt Missing: archive.txt Cleaned up: true

အရိပ်အမြွက် ကြည့်ရန်

Files.walk(root) က parent ကို child တွေထက် အရင် ပြန်ပေးလို့ sorted(Comparator.reverseOrder()) နဲ့ အစဉ်ပြောင်းရင် အတွင်းဆုံး file တွေ အရင်ဖျက်ပြီး folder ကို နောက်ဆုံးမှ ဖျက်ပါမယ်။ NoSuchFileException ရဲ့ getFile() က path string ပြန်ပေးလို့ Path.of(...).getFileName() နဲ့ နာမည်ပဲ ယူပါ။

အဖြေ ကြည့်ရန်
Main.java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class Main {
  static Path safeResolve(Path root, String name) {
    Path target = root.resolve(name).normalize();
    if (!target.startsWith(root)) {
      throw new IllegalArgumentException("outside the notes folder: " + name);
    }
    return target;
  }

  static void addNote(Path file, String note) throws IOException {
    Files.writeString(file, note + "\n", StandardCharsets.UTF_8,
        StandardOpenOption.CREATE, StandardOpenOption.APPEND);
  }

  static void deleteTree(Path root) throws IOException {
    try (Stream<Path> paths = Files.walk(root)) {
      for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
        Files.delete(p);
      }
    }
  }

  public static void main(String[] args) throws IOException {
    Path root = Files.createTempDirectory("notes-").toAbsolutePath().normalize();
    try {
      Path notes = safeResolve(root, "notes.txt");
      addNote(notes, "buy milk");
      addNote(notes, "call Aye");
      addNote(notes, "pay rent");

      List<String> lines = Files.readAllLines(notes, StandardCharsets.UTF_8);
      System.out.println("Notes: " + lines.size());
      for (int i = 0; i < lines.size(); i++) {
        System.out.println((i + 1) + ". " + lines.get(i));
      }

      try {
        safeResolve(root, "../secret.txt");
      } catch (IllegalArgumentException e) {
        System.out.println("Blocked: " + e.getMessage());
      }

      try {
        Files.readString(safeResolve(root, "archive.txt"), StandardCharsets.UTF_8);
      } catch (NoSuchFileException e) {
        System.out.println("Missing: " + Path.of(e.getFile()).getFileName());
      }
    } finally {
      deleteTree(root);
    }
    System.out.println("Cleaned up: " + !Files.exists(root));
  }
}

Quick Quiz 1 / 3

notes.txt ထဲမှာ "a" ရှိနေတုန်း Files.writeString(notes, "b") ကို option မပါဘဲ ခေါ်ရင် file ထဲမှာ ဘာကျန်မလဲ။

Quick Quiz 2 / 3

root က /data/uploads ဆိုရင် root.resolve("../secret.txt").startsWith(root) က ဘာပြန်မလဲ။

Quick Quiz 3 / 3

2 GB log file ထဲက ERROR line တွေကို ရေတွက်ဖို့ ဘယ်နည်းက အသင့်တော်ဆုံးလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Path က disk ကို မထိတဲ့ လိပ်စာ value ဖြစ်ပြီး Files ရဲ့ static method တွေက disk ပေါ်မှာ တကယ် အလုပ်လုပ်ပါတယ်။
  • StandardCharsets.UTF_8 ကို အမြဲ ပြတ်ပြတ်သားသား ပေးပါ၊ writeString() က default အနေနဲ့ overwrite လုပ်ပြီး APPEND မှ ဆက်ထည့်ပါတယ်။
  • File ကြီးတွေကို BufferedReader ဒါမှမဟုတ် Files.lines() နဲ့ ဖတ်ပြီး stream/reader တွေကို try-with-resources နဲ့ ပိတ်ပါ။
  • User input က path တွေကို normalize() လုပ်ပြီးမှ startsWith(root) နဲ့ စစ်ပါ၊ temp file တွေကို finally ထဲမှာ ရှင်းပါ။

java.nio.file API — Oracle

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

File I/O with Path & Files | Thuta Learning