Java IO操作:FileInputStream读取错误案例

原创 快来打我* 2024-12-12 15:15 89阅读 0赞

在Java中,FileInputStream用于从文件中读取数据。如果在使用过程中遇到错误,通常会涉及到各种异常。以下是一个错误案例:

  1. import java.io.FileInputStream;
  2. public class readFileError {
  3. public static void main(String[] args) {
  4. // 错误:尝试读取不存在的文件
  5. FileInputStream fis = new FileInputStream("non_existent_file.txt");
  6. try {
  7. byte[] content = new byte[1024]; // 读取1KB的数据
  8. int bytesRead = fis.read(content); // 错误:未检查读取数据是否完整
  9. if (bytesRead != -1) { // -1代表EOF
  10. System.out.println("Content: " + new String(content, 0, bytesRead)));
  11. } else {
  12. System.out.println("Failed to read file.");
  13. }
  14. } catch (Exception e) {
  15. System.out.println("Error reading file: " + e.getMessage());
  16. } finally {
  17. if (fis != null) {
  18. fis.close();
  19. }
  20. }
  21. }
  22. }

在这个错误案例中,我们试图读取一个不存在的文件。这会导致FileNotFoundException异常,但我们没有正确处理这个异常,导致程序运行异常。

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

发表评论

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

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

相关阅读