Java中IO流的读写操作,如何处理异常情况?实例展示

原创 青旅半醒 2024-11-30 16:51 104阅读 0赞

在Java中,IO流的读写操作通常会使用try-catch语句来处理可能发生的异常。

以下是一些常见的IO流操作以及对应的异常处理示例:

  1. FileInputStream - 读取文件内容
  1. import java.io.FileInputStream;
  2. import java.io.IOException;
  3. public class FileInputStreamExample {
  4. public static void main(String[] args) {
  5. try (FileInputStream fis = new FileInputStream("test.txt")) {
  6. byte[] buffer = new byte[1024];
  7. int length = fis.read(buffer);
  8. while (length != -1) {
  9. System.out.println(new String(buffer, 0, length))));
  10. length = fis.read(buffer);
  11. }
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. System.out.println("Error reading file: " + e.getMessage());
  15. }
  16. }
  17. }
  1. PrintWriter - 写入数据到文件或打印
  1. import java.io.FileWriter;
  2. import java.io.IOException;
  3. public class PrintWriterExample {
  4. public static void main(String[] args) {
  5. try (FileWriter writer = new FileWriter("test.txt")) {
  6. PrintWriter printWriter = new PrintWriter(writer);
  7. printWriter.println("Hello, World!");
  8. printWriter.close();
  9. } catch (IOException e) {
  10. e.printStackTrace();
  11. System.out.println("Error writing to file: " + e.getMessage());
  12. }
  13. }
  14. }

在上述示例中,如果文件不存在或者无法写入,FileInputStreamFileWriter会抛出异常。我们通过try-catch语句来捕获这些异常,并处理它们。

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

发表评论

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

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

相关阅读