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 void uploadFile(String uploadUrl, String uploadFile, String newName) {
    String LINE_END = "\r\n";     //数据结束标志
    String PREFIX = "--";        //数据前缀
    String BOUNDARY = "*****";    //边界标识
    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.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type",
            "multipart/form-data;boundary=" + BOUNDARY);
        // 文件输出流
        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);
            }
            System.out.println(result.toString());
        }
        ds.close();
    } catch (MalformedURLException e) {
           e.printStackTrace();
    } catch (IOException e) {
           e.printStackTrace();
    }
}

 

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;
    }
}

 

你可能感兴趣的:(java文件下载,上传,解压方法)