Java标准库中的IO操作:文件读写、网络通信问题案例
Java标准库中的IO(Input/Output)操作主要包括文件和网络通信的处理。以下是一些具体问题案例:
文件读写:
- 案例:读取一个文本文件。
try {
File file = new File("filename.txt"); // 请替换为实际文件路径
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line); // 打印读取到的每一行
}
scanner.close(); // 关闭资源,防止内存泄露
} catch (FileNotFoundException e) {
e.printStackTrace();
}
案例:将一个文本文件写入另一个位置。
try {
File inputFile = new File("input.txt"); // 请替换为实际输入文件路径
String output = "output.txt"; // 输出文件的名称
FileWriter writer = new FileWriter(output);
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
writer.write(line + "\n")); // 每行末尾添加换行符
}
scanner.close(); // 关闭资源,防止内存泄露
writer.close(); // 关闭文件写入流,防止资源泄漏
} catch (IOException e) {
e.printStackTrace();
}
- 案例:读取一个文本文件。
网络通信:
- 案例:客户端向服务器发起HTTP请求。
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
- 案例:客户端向服务器发起HTTP请求。
public class HttpClientExample {
public static void main(String[] args) {
// 创建URL对象
URL url = new URL(“http://example.com/api/data“);
try (HttpURLConnection connection = (HttpURLConnection) url.openConnection();) {
// 设置请求方法(GET或POST等)
connection.setRequestMethod("GET");
// 如果需要发送数据,设置为POST请求
// connection.setDoOutput(true);
// String dataToSend = "your-data-to-send"; // 请替换为你需要发送的实际数据
// connection.getOutputStream().write(dataToSend.getBytes()); // 发送数据
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null)) {
content.append(line).append("\n");
}
System.out.println(content.toString()); // 打印返回的内容
} else {
System.out.println("Error occurred. Response Code: " + responseCode); // 输出错误信息和响应码
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Failed to execute HTTP request due to an exception: " + e.getMessage()); // 输出错误信息
}
}
}
```
以上案例展示了Java标准库中的IO操作,包括文件读写和网络通信。
还没有评论,来说两句吧...