读取网盘文件下载到服务器

public void download(String url,String fileName) {
			
			String path = request.getSession().getServletContext()
					.getRealPath("/data/file/")+"/"+fileName;
			
			
			File directory = new File(request.getSession().getServletContext()
					.getRealPath("/data/file/"));
			if(!directory.exists()){
				//创建目录
				boolean result = directory.mkdirs();
				if(!result){
					logger.error("创建目录失败!");
				}
			}
			try {
				getURLResource(path,url);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		
		
	}
	
	//存图片到服务器上
	 public static void getURLResource(String ourputFile,String urlStr) throws Exception

	 {   
		 URL url = new URL(urlStr);  
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
         conn.setRequestMethod("GET");  
         conn.setConnectTimeout(5 * 1000);  
         InputStream inStream = conn.getInputStream();//通过输入流获取图片数据  
         byte[] btImg = readInputStream(inStream);//得到图片的二进制数据  
		
	        
	        File file = new File(ourputFile);  
            FileOutputStream fops = null;  
            try 
			{
            	fops = new FileOutputStream(file);
                fops.write(btImg);  
                fops.flush();  
                fops.close(); 
			} 
			catch (Exception e) 
			{	
				try
				{
					if( fops!=null )
					{
						fops.close();
					}
					
				}
				catch( Exception ex )
				{
					ex.printStackTrace();
				}
				e.printStackTrace();
			}
       
	 }
	 
	   public static byte[] readInputStream(InputStream inStream) throws Exception{  
	        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
	        byte[] buffer = new byte[1024];  
	        int len = 0;  
	        while( (len=inStream.read(buffer)) != -1 ){  
	            outStream.write(buffer, 0, len);  
	        }  
	        inStream.close();  
	        return outStream.toByteArray();  
	    }  
		  


你可能感兴趣的:(公司框架)