Java文件读写:FileNotFoundException实战演练
在Java中,FileNotFoundException
是用于表示文件无法被找到的一个异常。以下是一些关于该异常的实战演练:
- 文件不存在:
```java
import java.io.File;
public class FileNotFoundErrorExample {
public static void main(String[] args) {
File file = new File(“non_existent_file.txt”);
try {
// 读取文件,这将引发FileNotFoundException
System.out.println(file.read());
} catch (FileNotFoundException e) {
e.printStackTrace();
// 指出错误并处理
System.out.println("Error: The file does not exist.");
}
}
}
2. 文件名拼写错误:
```java
// 拼写错误的文件名
File wrongName = new File("wrongfilename.txt");
try {
System.out.println(wrongName.read()); // 会抛出FileNotFoundException
} catch (FileNotFoundException e) {
System.out.println("Error: The file does not exist.");
}
- 文件被移动或删除:
```java
// 确保此文件存在
File existingFile = new File(“existingfile.txt”);
try {
// 移动文件,这将导致FileNotFoundException
existingFile.delete();
File movedFile = new File(“/path/to/destination/“ + “movedfile.txt”));
System.out.println(movedFile.read()); // 会抛出FileNotFoundException
} catch (FileNotFoundException e) {
System.out.println(“Error: The file does not exist.”);
}``
这些实战演练展示了在Java中如何处理
FileNotFoundException`。
还没有评论,来说两句吧...