读取网络文件写入本地

import java.io.*;
import java.net.URL;
import java.util.zip.GZIPOutputStream;

/**
 * Created with IntelliJ IDEA.
 * User: smy
 * Date: 2020/3/17
 * Time: 10:37
 * Description: No Description
 */
public class FileUtils {
    /**
     * 获取文件、二进制byte数组
     * @param arg
     * @return
     */
    public static byte[] getFileByteArray(String arg){
        ByteArrayOutputStream byteArr = new ByteArrayOutputStream();
        try {
            URL url = new URL(arg);
            InputStream in = url.openStream();
            byte[] buf = new byte[1024];
            int length = 0;
            while((length = in.read(buf)) != -1){
                byteArr.write(buf,0,length);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return byteArr.toByteArray();
    }
    /**
     * 获取网络文件并写入本地   测试用
     * @param arg
     * @return
     */
    public static void getFileByteArrAndWrite(String arg){
        byte[] byteArray = getFileByteArray(arg);
        byte[] bytes = compress(byteArray);
        //String json = new String(Base64.encodeBase64(bytes));
        File file = new File("H://new.xlsx");
        try {
            file.createNewFile();
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(byteArray);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] compress(byte[] data) {
        //System.out.println("before:" + data.length);

        GZIPOutputStream gzip = null ;
        ByteArrayOutputStream baos = null ;
        byte[] newData = null ;

        try {
            baos = new ByteArrayOutputStream() ;
            gzip = new GZIPOutputStream(baos);

            gzip.write(data);
            gzip.finish();
            gzip.flush();

            newData = baos.toByteArray() ;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                gzip.close();
                baos.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //System.out.println("after:" + newData.length);
        return newData ;
    }

    public static void main(String[] args) {
        getFileByteArrAndWrite("http://10.0.6.44/upload/public/0/4d90b2ad1a1249369a2888f07bffa976@付款计划-业务版 (2).xlsx");
        //getFileByteArrAndWrite("http://10.0.6.44/upload/public/0/889a2873ccf54431a1053f9b7fc99f0e@9df1692fe9b1dcb2b4fa55d380e1be64.jpg");
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值