okhttp下载文件 Java下载文件 javaokhttp下载文件 下载文件 java下载 okhttp下载 okhttp

okhttp下载文件 Java下载文件 javaokhttp下载文件 下载文件 java下载 okhttp下载 okhttp


示例 http客户端 用的是 okhttp,也可以用 UrlConnetcion或者apache

1、引入Maven

okhttp官网

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.14.9</version>
</dependency>

也可以下载 okhttp jar方式引入

1.1、okhttp发起请求官网Demo

public static final MediaType JSON = MediaType.get("application/json");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(json, JSON);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

2、下载文件

public class TestDownload {

    public static void main(String args[]) {
       // 图片文件地址
        String url = "https://himg.bdimg.com/sys/portraitn/item/public.1.c9145b32.BtcNjpu-t6NEqWtWFh3ICg";
        
        // 创建一个 okhttp客户端线程池
        OkHttpClient client = new OkHttpClient.Builder()
                .connectionPool(new ConnectionPool(20, 2, TimeUnit.MINUTES))
                .build();
        
        // 构建请求对象
        Request request = new Request.Builder().url(url).get().build();
        
        // 发起请求得到请求结果
        Response response = client.newCall(request).execute();
        
        // 获取请求结果
        ResponseBody responseBody = response.body();
        if (null != responseBody) {
            // 获取文件后缀类型 可以使用 responseBody.contentType() 获取 ContentType,我这边知道这个url文件的类型
            String suffix = ".jpeg";
            
            // 创建一个文件
            String filename = "E:\\test\\" + System.currentTimeMillis() + suffix;
            
            File file = new File(filename);
    
            // 判断目录是否存在,不存在则创建目录
    
            File parent = new File(file.getParent());
            if(!parent.exists()){
                parent.mkdir();
            }
            
            // 判断文件是否存在, 不存在创建文件
            if (!file.exists()) {
                if (file.createNewFile()) {
                    // 获取请求结果输入流
                    InputStream rInputStream = responseBody.byteStream();
                    
                    // 创建读取字节流的byte数组
                    byte[] buffer = new byte[500];
                    
                    int areRead;
                    
                    // 创建文件输出流
                    FileOutputStream outputStream = new FileOutputStream(file );
                    
                    // 使用输入流读取字节,在输出到文件
                    while ((areRead = rInputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, areRead);
                    }
                    rInputStream.close();
                    outputStream.close();
                }
            }
        }
        response.close();
    }
}

3、扩充,读写 txt文件内容

3.1读写内容

    /**
     * 创建文件以及文件对应的目录
     * @param path 文件路径,例如 E:\test\测试.txt
     * @return {@link File}
     */
    private File createFile(String path) throws IOException {
        File file = new File(path);
        
        // 判断目录是否存在
        File parent = new File(file.getParent());
        if(!parent.exists()){
            parent.mkdir();
        }
        
        if(!file.exists()){
            file.createNewFile();
        }
        return file;
    }
    
    /**
     * 读取txt内容
     * @param file {@link File}
     * @return 字符串
     */
    private String readTxt(File file) throws IOException {
        
        StringBuilder sb = new StringBuilder();
        
        // 使用字符流读取
        BufferedReader reader = new BufferedReader(new FileReader(file));
        
        // 读取每一行的内容
        String readLine;
        
        while ((readLine = reader.readLine()) != null){
            sb.append(readLine);
        }
    
        String result = sb.toString();
        
        System.out.printf("读取内容: \n %s", result);
        
        reader.close();
        
        /*
        // 使用字节流读取
        long fileLength = file.length();
        
        // 创建一个用于读取指定字节大小的数组
        byte[] bytes = new byte[(int) fileLength];
        
        // 创建一个文件输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        
        // 使用 文件输入流读取字节输入到 字节数组中
        int areRead = fileInputStream.read(bytes);
        
        String result2 = new String(bytes);

        fileInputStream.close();
   
         */
        return result;
    }
    
    @Test
    public void writeTxt() throws IOException {
        String path = "E:\\test2\\测试.txt";
        
        File file = createFile(path);
        
        // 读取现在已有的内容
        String readTxt = readTxt(file);
        
        // 创建一个文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        
        // 之前的内容
        fileOutputStream.write(readTxt.getBytes(StandardCharsets.UTF_8));
    
        // 换行, 使用Java的自定义换行符号,会根据不同系统平台转义
        String newLine = System.getProperty("line.separator");
        fileOutputStream.write(newLine.getBytes());
        
        // 追加的内容
        fileOutputStream.write((String.valueOf(System.currentTimeMillis()) + " \r\n").getBytes(StandardCharsets.UTF_8));
        
        // 关闭资源
        fileOutputStream.flush();
        fileOutputStream.close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值