Java中的IO操作:文件读写与网络通信的实战案例
在Java中,IO操作主要包括文件读写和网络通信。以下是一些实战案例:
文件读写:
- 打开文件:
File file = new File("path/to/file.txt"); FileInputStream fis = new FileInputStream(file);
- 读取文件内容:
String content = new String(fis.readAllBytes()));
- 关闭文件:
fis.close(); file.close();
- 打开文件:
网络通信:
- 发送HTTP请求(使用第三方库,如Apache HttpClient):
CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/api/data"); StringEntity stringEntity = new StringEntity("your data here"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); CloseableHttpResponse response = httpClient.execute(httpPost);
- 接收HTTP响应(同样使用第三方库):
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))); StringBuilder contentBuilder = new StringBuilder(); String line; while ((line = br.readLine()) != null) { contentBuilder.append(line).append("\n"); } br.close(); response.close(); Content content = new Content(contentBuilder.toString())); // 处理content对象
- 发送HTTP请求(使用第三方库,如Apache HttpClient):
以上案例涵盖了Java文件读写和网络通信的基本操作,可以根据实际需求进行调整。
还没有评论,来说两句吧...