Cách khởi tạo thư mục trong Java

Trong Java để khởi tạo một thư mục chúng ta có thể sử dụng Java IO hoặc Java NIO. 

Java NIO

Java NIO là một phiên bản nâng cấp của JavaIO với nhiều API tiện lợi và mang lại hiệu năng cao hơn. Chúng ta có thể sử dụng Files.createDirectory để khởi tạo một thư mục hoặc Files.createDirectories để khởi tạo các thư mục bao gồm các thư mục cha nếu chúng chưa tồn tại.

Files.createDirectory

Files.createDirectory được dùng để khởi tạo một thư mục tuy nhiên có một số lưu ý chúng ta cần xem xét:

  • Nếu thư mục cha không tồn tại nó sẽ ném NoSuchFileException.
  • Nếu thư mục đích đã tồn tại nó sẽ ném FileAlreadyExistsException.
  • Nếu có bất kỳ IO error nào thì nó sẽ ném IOException.
  Path path = Paths.get("/home/document/project/myfolder");
  Files.createDirectory(path);

Ví dụ đối với đoạn code trên, nếu các thư mục cha của myfolder như project hoặc document không tồn tại thì nó sẽ ném NoSuchFileException.

Files.createDirectories

Files.createDirectories là cách hoàn hảo để khắc phục nhược điểm của Files.createDirectory trong trường hợp các thư mục cha chưa tồn tại trước đó thì chúng sẽ được khởi tạo trước.

Nếu thư mục đích đã tồn tại thì Files.createDirectories sẽ bỏ qua thay vì ném lỗi FileAlreadyExistsException như Files.createDirectory.

Path path = Paths.get("/home/document/project/myfolder");
Files.createDirectories(path);

Các bạn có thể tham khảo mã nguồn đầy đủ như code bên dưới.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) {

        Path path = Paths.get("/home/document/project/myfolder");
        try {
            Files.createDirectories(path);

            System.out.println("Directory is created!");
        } catch (IOException e) {
            System.err.println("Failed to create directory!" + e.getMessage());
        }

    }
}

Java IO

Trong một khoảng thời gian dài việc sử dụng Java IO để tạo một thư mục có lẽ sẽ quen thuộc với chúng ta hơn thông qua java.io.File class với method file.mkdir() để khởi tạo một thư mục mới hoặc file.mkdirs() để khởi tạo một thư mục bao gồm các thư mục cha nếu chúng chưa tồn tại trước đó.

Trong hầu hết các trường hợp thì chúng ta nên sử dụng file.mkdirs() để toàn vì nó sẽ giúp khởi tạo các thư mục cha nếu chưa tồn tại.

import java.io.File;

public class Main {

    public static void main(String[] args) {

        String dir = "/home/document/project/myfolder";

        File file = new File(dir);

        if (file.mkdirs()) {
            System.out.println("Directory is created!");
        } else {
            System.out.println("Failed to create directory!");
        }

    }

}

Cả 2 method file.mkdir và file.mkdirs đều trả về true nếu thư mục được khởi tạo thành công.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x