Trang chủHướng dẫnTạo file trong Java: Hướng dẫn chi tiết với ví dụ
Java

Tạo file trong Java: Hướng dẫn chi tiết với ví dụ

CyStack blog 4 phút để đọc
CyStack blog26/09/2025
Locker Avatar

Bao Tran

Web Developer

Locker logo social
Reading Time: 4 minutes

Bạn muốn học cách tạo file trong Java? Bài viết này sẽ hướng dẫn bạn các cách phổ biến để tạo file bằng lớp File, FileOutputStreamFiles, kèm ví dụ minh họa dễ hiểu để bạn áp dụng ngay vào dự án của mình.

Tạo file trong Java

3 phương pháp phổ biến để tạo file trong Java

1. File.createNewFile()

Lớp java.io.File có thể được sử dụng để tạo một file mới trong Java. Khi khởi tạo một File object, chúng ta cung cấp tên file và sau đó có thể gọi method createNewFile() để tạo file mới trong Java. Method File createNewFile() trả về true nếu file mới được tạo và false nếu file đã tồn tại. Method này cũng có thể ném ra java.io.IOException khi không thể tạo file. File được tạo ra sẽ trống và có kích thước 0 byte. Khi tạo File object bằng cách truyền vào tên file, chúng ta có thể dùng absolute path (đường dẫn tuyệt đối), hoặc chỉ cung cấp tên file, hoặc cung cấp đường dẫn tương đối. Với non-absolute path, File object sẽ cố gắng tìm file trong project root directory. Nếu chạy chương trình từ command line, đối với non-absolute path, File object sẽ tìm file từ current directory. Khi tạo file path, chúng ta nên sử dụng System property file.separator để chương trình có thể platform independent (nền tảng độc lập). Hãy cùng xem các trường hợp khác nhau với một chương trình Java đơn giản để tạo file mới.

package com.journaldev.files;

import java.io.File;
import java.io.IOException;

public class CreateNewFile {

    /**
     * This class shows how to create a File in Java
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        String fileSeparator = System.getProperty("file.separator");
        
        //absolute file name with path
        String absoluteFilePath = fileSeparator+"Users"+fileSeparator+"pankaj"+fileSeparator+"file.txt";
        File file = new File(absoluteFilePath);
        if(file.createNewFile()){
            System.out.println(absoluteFilePath+" File Created");
        }else System.out.println("File "+absoluteFilePath+" already exists");
        
        //file name only
        file = new File("file.txt");
        if(file.createNewFile()){
            System.out.println("file.txt File Created in Project root directory");
        }else System.out.println("File file.txt already exists in the project root directory");
        
        //relative path
        String relativePath = "tmp"+fileSeparator+"file.txt";
        file = new File(relativePath);
        if(file.createNewFile()){
            System.out.println(relativePath+" File Created in Project root directory");
        }else System.out.println("File "+relativePath+" already exists in the project root directory");
    }

}

Khi chúng ta chạy chương trình trên từ Eclipse IDE lần đầu tiên, kết quả sau sẽ được tạo ra.

/Users/pankaj/file.txt File Created
file.txt File Created in Project root directory
Exception in thread "main" 
java.io.IOException: No such file or directory
	at java.io.UnixFileSystem.createFileExclusively(Native Method)
	at java.io.File.createNewFile(File.java:947)
	at com.journaldev.files.CreateNewFile.main(CreateNewFile.java:32)

Đối với relative path, chương trình ném ra IOException vì thư mục tmp không tồn tại trong project root folder. Như vậy có thể thấy rằng createNewFile() chỉ cố gắng tạo file, và bất kỳ thư mục nào (dù absolute hay relative) đều phải tồn tại sẵn, nếu không sẽ ném ra IOException. Vì vậy, mình đã tạo thư mục “tmp” trong project root và chạy lại chương trình, dưới đây là kết quả.

File /Users/pankaj/file.txt already exists
File file.txt already exists in the project root directory
tmp/file.txt File Created in Project root directory

Hai file đầu tiên đã tồn tại sẵn, nên createNewFile() trả về false, file thứ ba được tạo trong thư mục tmp và trả về true. Bất kỳ lần chạy tiếp theo nào cũng sẽ cho ra kết quả sau:

File /Users/pankaj/file.txt already exists
File file.txt already exists in the project root directory
File tmp/file.txt already exists in the project root directory

Nếu bạn chạy cùng chương trình đó từ terminal classes directory, thì kết quả sẽ như sau.

//first execution from classes output directory	
pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFile
File /Users/pankaj/file.txt already exists
file.txt File Created in Project root directory
Exception in thread "main" java.io.IOException: No such file or directory
	at java.io.UnixFileSystem.createFileExclusively(Native Method)
	at java.io.File.createNewFile(File.java:947)
	at com.journaldev.files.CreateNewFile.main(CreateNewFile.java:32)

//tmp directory doesn't exist, let's create it
pankaj:~/CODE/JavaFiles/bin$ mkdir tmp

//second time execution
pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFile
File /Users/pankaj/file.txt already exists
File file.txt already exists in the project root directory
tmp/file.txt File Created in Project root directory

//third and subsequent execution
pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFile
File /Users/pankaj/file.txt already exists
File file.txt already exists in project root directory
File tmp/file.txt already exists in project root directory

2. FileOutputStream.write(byte[] b)

Nếu bạn muốn tạo một file mới và đồng thời ghi một số dữ liệu vào đó, bạn có thể sử dụng method FileOutputStream.write. Dưới đây là một đoạn code đơn giản minh họa cách sử dụng. Các quy tắc về absolute path (đường dẫn tuyệt đối) và relative path (đường dẫn tương đối) đã đề cập ở trên cũng được áp dụng trong trường hợp này.

String fileData = "Pankaj Kumar";
FileOutputStream fos = new FileOutputStream("name.txt");
fos.write(fileData.getBytes());
fos.flush();
fos.close();

3. Java NIO Files.write()

Chúng ta có thể sử dụng lớp Java NIO Files để tạo một file mới và ghi một số dữ liệu vào đó. Đây là một lựa chọn tốt vì chúng ta không cần phải lo lắng về việc đóng các tài nguyên IO.

String fileData = "Pankaj Kumar";
Files.write(Paths.get("name.txt"), fileData.getBytes());

Đó là tất cả về việc tạo một file mới trong chương trình Java.

Bạn có thể tham khảo thêm nhiều ví dụ về core Java trong GitHub Repository của chúng tôi.

0 Bình luận

Đăng nhập để thảo luận

Chuyên mục Hướng dẫn

Tổng hợp các bài viết hướng dẫn, nghiên cứu và phân tích chi tiết về kỹ thuật, các xu hướng công nghệ mới nhất dành cho lập trình viên.

Đăng ký nhận bản tin của chúng tôi

Hãy trở thành người nhận được các nội dung hữu ích của CyStack sớm nhất

Xem chính sách của chúng tôi Chính sách bảo mật.

Đăng ký nhận Newsletter

Nhận các nội dung hữu ích mới nhất