zoukankan      html  css  js  c++  java
  • java http下载文件/上传文件保存

    private boolean downloadFile(String httpUrl, String savePath) {
            int byteread = 0;
            try {
                URL url = new URL(httpUrl);
                URLConnection conn = url.openConnection();
                InputStream inStream = conn.getInputStream();
                FileOutputStream fs = new FileOutputStream(savePath);
                byte[] buffer = new byte[1204];
                while ((byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
                System.out.println(savePath+" download finished!");
                return true;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

     上传文件保存在服务器:

    private String saveFile(MultipartFile file) {
    		try {
    			if(file != null && !file.isEmpty()) {
    				
    				String filePath = "保存至服务器的地址"
    				File fp = new File(new File(filePath).getParent());
    				if(!fp.exists()){
    					fp.mkdirs();
    				}
    				DataOutputStream out = new DataOutputStream(new FileOutputStream(filePath));
    				InputStream is = null;
    				try {
    					is = file.getInputStream();
    					byte[] b=new byte[is.available()];
    					is.read(b);
    					out.write(b);
    					return filePath ;
    				} catch (Exception e) {
    					throw new RuntimeException(e);
    				} finally {
    					if (is != null) {
    						is.close();
    					}
    					if (out != null) {
    						out.close();
    					}
    				}
    			}
    		} catch (Exception e) {
    			throw new RuntimeException(e);
    		}
    		return null;
    	}
    
  • 相关阅读:
    2017中国大学生程序设计竞赛
    2017中国大学生程序设计竞赛
    2017中国大学生程序设计竞赛
    2017中国大学生程序设计竞赛
    计算几何之凸包模板
    计算几何之凸包模板
    Kafka知识点汇总
    python 爬虫1 開始,先拿新浪微博開始
    iOS 7的手势滑动返回
    Ctrl+Enter 选中文本提交
  • 原文地址:https://www.cnblogs.com/zhangfei/p/4153797.html
Copyright © 2011-2022 走看看