Java中IO流操作的异常处理策略实例展示
在Java中,IO流操作可能会抛出各种异常。以下是一个关于文件读写、网络连接等常见IO异常处理策略的实例:
- 文件读写异常处理
import java.io.*;
public class FileOperation {
public static void main(String[] args) {
String filePath = "path_to_your_file.txt"; // 要操作的文件路径
try {
// 打开文件以读取
File file = new File(filePath);
BufferedReader reader = new BufferedReader(new FileReader(file)));
// 读取并处理文件内容
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 输出到控制台
}
// 关闭读取的文件
reader.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error occurred: " + e.getMessage());
}
}
}
- 网络连接异常处理
import java.io.*;
import java.net.*;
public class NetworkOperation {
public static void main(String[] args) {
String url = "http://example.com"; // 要访问的URL
try {
// 创建Socket对象并连接到指定URL
Socket socket = new Socket(new URL(url).getHost(), 80); // 通常HTTP服务端口是80
// 创建流并开始读写数据
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))));
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()))));
// 发送请求(这里假设为GET)
String request = "GET /index.html HTTP/1.1\r\n\r\n";
out.writeBytes(request);
// 读取并处理服务器响应
String responseLine;
while ((responseLine = in.readLine()) != null) {
System.out.println(responseLine); // 输出到控制台
}
// 关闭流和Socket连接
in.close();
out.close();
socket.close();
} catch (IOException e) {
System.err.println("I/O error occurred: " + e.getMessage());
}
}
}
以上代码中,异常处理策略主要通过try-catch语句块来实现。当IO操作抛出异常时,程序会立即跳转到相应的catch块,执行相应的错误处理逻辑。
还没有评论,来说两句吧...