java文件下载,上传,解压方法

1、文件下载(亲测可用)

private static final int BUFFER = 2 * 1024;// 缓冲区大小(2k)
private boolean isSuccess = true;//成功标志
public void downFile(String urlStr, String path, String fileName) {
    OutputStream output = null;
    try {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 取得inputStream,并将流中的信息写入

        String pathName = path + fileName;// 文件存储路径

        File file = new File(pathName);
        InputStream input = conn.getInputStream();
        if (file.exists()) {
            return;
        } else {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file.createNewFile();// 新建文件
            output = new FileOutputStream(file);
            int count;
            byte[] buffer = new byte[2 * 1024];
            while ((count = input.read(buffer)) != -1) {
                output.write(buffer, 0, count);
            }
            output.flush();
        }
        output.close();
    } catch (Exception e) {
        e.printStackTrace();
        isSuccess = false;
    }
}

 

2、文件上传

public String uploadFile(String uploadUrl, String uploadFile, String newName) {
    String LINE_END = "\r\n";     //数据结束标志
    String PREFIX = "--";        //数据前缀
    String BOUNDARY = "*****";    //边界标识
    String resultStr = "";
try { URL url = new URL(uploadUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // 允许Input、Output,不使用Cache con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // 设置传送的method=POST con.setRequestMethod("POST");
     con.setConnectTimeout(120 * 1000);// (单位:毫秒)
con.setReadTimeout(60 * 1000);// (单位:毫秒)
// 设置请求属性 con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
con.connect();
// 文件输出流 DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(PREFIX + BOUNDARY + LINE_END); ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + newName + "\"" + LINE_END); ds.writeBytes(LINE_END); // 取得文件的FileInputStream FileInputStream fStream = new FileInputStream(uploadFile); byte[] buffer = new byte[BUFFER]; int length = -1; while ((length = fStream.read(buffer)) != -1) { ds.write(buffer, 0, length); } ds.writeBytes(LINE_END); ds.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END); fStream.close(); ds.flush(); // 取得Response内容 int resCode = con.getResponseCode(); if (resCode == 200) { InputStream is = con.getInputStream(); int ch; StringBuffer result = new StringBuffer(); while ((ch = is.read()) != -1) { result.append((char) ch); }
       resultStr = result.toString(); } ds.close(); }
catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
  return resultStr ; }

 

3、文件解压(亲测可用)

public void UnZipFolder(String zipFileString, String outPathString) {
    File desDir = new File(outPathString);
    if (!desDir.exists()) {
        desDir.mkdirs();
    }
    try {
        @SuppressWarnings("resource")
        ZipFile zf = new ZipFile(zipFileString);//根据文件创建ZipFile
        //遍历压缩文件条目
        for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            //获取条目的输入流
            InputStream in = zf.getInputStream(entry);
            String str = outPathString + entry.getName();//条目路径
            str = new String(str.getBytes("8859_1"), "GB2312");
            File desFile = new File(str);
            if (!desFile.exists()) {
                File fileParentDir = desFile.getParentFile();
                if (!fileParentDir.exists()) {
                    fileParentDir.mkdirs();
                }
                desFile.createNewFile();//创建新文件
            }
            OutputStream out = new FileOutputStream(desFile);
            byte buffer[] = new byte[2 * 1024];
            int realLength;
            while ((realLength = in.read(buffer)) > 0) {
                out.write(buffer, 0, realLength);
            }
            in.close();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        isSuccess = false;
    }
}

 

转载于:https://www.cnblogs.com/pear-lemon/p/4831800.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值