Java中IO流操作:文件读写,网络通信等问题实例展示

原创 ゞ 浴缸里的玫瑰 2024-12-07 14:39 81阅读 0赞

在Java中,IO流是处理输入和输出数据的关键部分。以下是一些常见的IO流操作实例:

  1. 文件读写:
    ```java
    import java.io.*;

// 读取文件内容
File file = new File(“path_to_your_file.txt”);
BufferedReader br = new BufferedReader(new FileReader(file));
String content = “”;
while ((content = br.readLine()) != null) {
System.out.println(content);
}
br.close();

// 写入文件
String dataToWrite = “Hello, World!”;
FileOutputSteam fos = new FileOutputStream(“new_file.txt”);
fos.write(dataToWrite.getBytes());
fos.close();

  1. 2. 网络通信:
  2. ```java
  3. import java.io.*;
  4. import java.net.*;
  5. // 发送HTTP请求
  6. public class SendHTTPRequest {
  7. public static void main(String[] args) throws IOException {
  8. URL url = new URL("http://example.com");
  9. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  10. // 设置请求方法
  11. connection.setRequestMethod("GET");
  12. // 获取响应码
  13. int responseCode = connection.getResponseCode();
  14. System.out.println("Response Code: " + responseCode);
  15. if (responseCode == 200) { // 如果状态码为200(成功),则读取响应内容
  16. BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())));
  17. String responseContent = "";
  18. while ((responseContent = br.readLine()) != null) {
  19. System.out.println(responseContent);
  20. }
  21. br.close();
  22. }
  23. connection.disconnect(); // 关闭连接
  24. }
  25. }

以上实例展示了Java中文件读写和网络通信的基本操作。在实际项目中,可能需要处理更复杂的IO流问题。

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

发表评论

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

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

相关阅读