Java文件读写:IOException处理示例

原创 雨点打透心脏的1/2处 2024-12-08 13:06 169阅读 0赞

在Java中,进行文件读写操作时可能会抛出IOException。以下是一个简单的示例,展示了如何处理IOException。

  1. 文件写操作:
  1. import java.io.*;
  2. public class FileWriteExample {
  3. public static void main(String[] args) {
  4. // 创建一个Writer对象
  5. try (PrintWriter writer = new PrintWriter("test.txt")) {
  6. // 写入一些文本
  7. writer.println("This is a test write operation.");
  8. System.out.println("Text has been written successfully.");
  9. } catch (IOException e) {
  10. System.err.println("Error occurred while writing to file: " + e.getMessage());
  11. // 在这里,你可以选择记录错误信息、优雅降级或者干脆抛出异常
  12. }
  13. }
  14. }
  1. 文件读操作:
  1. import java.io.*;
  2. public class FileReadExample {
  3. public static void main(String[] args) {
  4. try (BufferedReader reader = new BufferedReader(new FileReader("test.txt")))) {
  5. String line;
  6. // 逐行读取文件内容
  7. while ((line = reader.readLine()) != null) {
  8. System.out.println(line);
  9. }
  10. System.out.println("File has been read successfully.");
  11. } catch (IOException e) {
  12. System.err.println("Error occurred while reading from file: " + e.getMessage());
  13. // 在这里,你可以选择记录错误信息、优雅降级或者干脆抛出异常
  14. }
  15. }
  16. }

在这个示例中,我们处理了 IOException。如果在读写文件时出现这类异常,我们会捕获它并根据需要进行适当的错误处理。

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

发表评论

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

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

相关阅读