Java文件读写:FileNotFoundException实战演练

原创 一时失言乱红尘 2024-10-18 09:45 137阅读 0赞

在Java中,FileNotFoundException是用于表示文件无法被找到的一个异常。以下是一些关于该异常的实战演练:

  1. 文件不存在:
    ```java
    import java.io.File;

public class FileNotFoundErrorExample {
public static void main(String[] args) {
File file = new File(“non_existent_file.txt”);

  1. try {
  2. // 读取文件,这将引发FileNotFoundException
  3. System.out.println(file.read());
  4. } catch (FileNotFoundException e) {
  5. e.printStackTrace();
  6. // 指出错误并处理
  7. System.out.println("Error: The file does not exist.");
  8. }
  9. }

}

  1. 2. 文件名拼写错误:
  2. ```java
  3. // 拼写错误的文件名
  4. File wrongName = new File("wrongfilename.txt");
  5. try {
  6. System.out.println(wrongName.read()); // 会抛出FileNotFoundException
  7. } catch (FileNotFoundException e) {
  8. System.out.println("Error: The file does not exist.");
  9. }
  1. 文件被移动或删除:
    ```java
    // 确保此文件存在
    File existingFile = new File(“existingfile.txt”);

try {
// 移动文件,这将导致FileNotFoundException
existingFile.delete();
File movedFile = new File(“/path/to/destination/“ + “movedfile.txt”));

  1. System.out.println(movedFile.read()); // 会抛出FileNotFoundException

} catch (FileNotFoundException e) {
System.out.println(“Error: The file does not exist.”);
}
`` 这些实战演练展示了在Java中如何处理FileNotFoundException`。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,137人围观)

还没有评论,来说两句吧...

相关阅读