Java中IO流操作的异常处理策略实例展示

原创 心已赠人 2024-12-04 01:48 83阅读 0赞

在Java中,IO流操作可能会抛出各种异常。以下是一个关于文件读写、网络连接等常见IO异常处理策略的实例:

  1. 文件读写异常处理
  1. import java.io.*;
  2. public class FileOperation {
  3. public static void main(String[] args) {
  4. String filePath = "path_to_your_file.txt"; // 要操作的文件路径
  5. try {
  6. // 打开文件以读取
  7. File file = new File(filePath);
  8. BufferedReader reader = new BufferedReader(new FileReader(file)));
  9. // 读取并处理文件内容
  10. String line;
  11. while ((line = reader.readLine()) != null) {
  12. System.out.println(line); // 输出到控制台
  13. }
  14. // 关闭读取的文件
  15. reader.close();
  16. } catch (FileNotFoundException e) {
  17. System.err.println("File not found: " + e.getMessage());
  18. } catch (IOException e) {
  19. System.err.println("I/O error occurred: " + e.getMessage());
  20. }
  21. }
  22. }
  1. 网络连接异常处理
  1. import java.io.*;
  2. import java.net.*;
  3. public class NetworkOperation {
  4. public static void main(String[] args) {
  5. String url = "http://example.com"; // 要访问的URL
  6. try {
  7. // 创建Socket对象并连接到指定URL
  8. Socket socket = new Socket(new URL(url).getHost(), 80); // 通常HTTP服务端口是80
  9. // 创建流并开始读写数据
  10. BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))));
  11. DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()))));
  12. // 发送请求(这里假设为GET)
  13. String request = "GET /index.html HTTP/1.1\r\n\r\n";
  14. out.writeBytes(request);
  15. // 读取并处理服务器响应
  16. String responseLine;
  17. while ((responseLine = in.readLine()) != null) {
  18. System.out.println(responseLine); // 输出到控制台
  19. }
  20. // 关闭流和Socket连接
  21. in.close();
  22. out.close();
  23. socket.close();
  24. } catch (IOException e) {
  25. System.err.println("I/O error occurred: " + e.getMessage());
  26. }
  27. }
  28. }

以上代码中,异常处理策略主要通过try-catch语句块来实现。当IO操作抛出异常时,程序会立即跳转到相应的catch块,执行相应的错误处理逻辑。

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

发表评论

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

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

相关阅读