FileNotFoundException trong Java

Trong bài viết này, chúng ta sẽ nói về một exception rất phổ biến trong Java – FileNotFoundException. Chúng ta sẽ xem xét một số trường hợp mà nó có thể xảy ra thông qua một số ví dụ cụ thể.

Khi nào FileNotFoundException xuất hiện?

Theo tài liệu của Java, FileNotFoundException sẽ xảy ra trong các trường hợp:

  • Một file được chỉ định với đường dẫn không tồn tại
  • Một file được chỉ định với đường dẫn tồn tại nhưng không thể truy xuất được vì một lý do gì đó chẳng hạn như không có quyền truy cập v.v

Làm thế nào để giải quyết FileNotFoundException

Đầu tiên chúng ta cần biết IOException là một exception thừa kế từ Exception class đại diện cho các exception liên quan đến các tác vụ IO. Sau đó chúng ta cần dùng try-catch để bắt các exception này và xử lý. Việc xử lý tùy vào trường hợp cụ thể, ví dụ như:

  • Thông báo lỗi cho người dùng rằng đường dẫn file đã bị sai.
  • Tạo file mới khi đường dẫn đến file không tồn tại.
  • Ghi log vào hệ thống.

Giả sử chúng ta có

class FileNotFoundExceptionTest {

    public void readFailingFile(String fileName) throws IOException {
        BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
        rd.readLine();
    }

    public static class BusinessException extends RuntimeException {
        public BusinessException(String string, FileNotFoundException ex) {
            super(string, ex);
        }
    }
}

Trong đó hàm readFailingFile sẽ gây exception vì đường dẫn được tạo cố tình được đặt giá trị giả.

Chúng ta có log lại exception để đội dev có thể xem và nhanh chóng khắc phục ngay sau đó.

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
    private static final Logger LOG = Logger.getLogger(String.valueOf(FileNotFoundExceptionTest.class));
    private static String fileName = Double.toString(Math.random());

    public static void main(String[] args) {
        try {
            FileNotFoundExceptionTest fileNotFoundExceptionTest = new FileNotFoundExceptionTest();
            fileNotFoundExceptionTest.readFailingFile(fileName);
        } catch (FileNotFoundException ex) {
            LOG.log(Level.CONFIG, "Optional file " + fileName + " was not found.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Hoặc ném một BussinessException lên và ứng dụng chịu trách nhiệm chuyển đổi exception này sang lời nhắn cho người dùng.

public class Main {
    private static final Logger LOG = Logger.getLogger(String.valueOf(FileNotFoundExceptionTest.class));
    private static String fileName = Double.toString(Math.random());

    public static void main(String[] args) {
        try {
            FileNotFoundExceptionTest fileNotFoundExceptionTest = new FileNotFoundExceptionTest();
            fileNotFoundExceptionTest.readFailingFile(fileName);
        } catch (FileNotFoundException ex) {
            throw new FileNotFoundExceptionTest.BusinessException(
                    "BusinessException: necessary file was not present.", ex);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Hoặc có thể tạo file mới nếu chưa tồn tại

import java.io.*;
import java.util.logging.Logger;

public class Main {
    private static final Logger LOG = Logger.getLogger(String.valueOf(FileNotFoundExceptionTest.class));
    private static String fileName = Double.toString(Math.random());

    public static void main(String[] args) {
        try {
            FileNotFoundExceptionTest fileNotFoundExceptionTest = new FileNotFoundExceptionTest();
            fileNotFoundExceptionTest.readFailingFile(fileName);
        } catch (FileNotFoundException ex) {
            try {
                new File(fileName).createNewFile();
            } catch (IOException ioe) {
                throw new RuntimeException(
                        "BusinessException: even creation is not possible.", ioe);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Nguồn

https://www.baeldung.com/java-filenotfound-exception

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