java 根據地址(鏈接)下載文件到本地


package com.sinosoft.cms.common.util;

//An highlighted block
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Caiji {

// public static void main(String[] args) throws UnsupportedEncodingException
// {
//
// String photoUrl = "http://XXXXXXXXXXXXXXX.pdf";
// //
//
// String fileName = photoUrl.substring(photoUrl.lastIndexOf("/")); //為下載的文件命名
// fileName = URLDecoder.decode(fileName,"utf-8");
// String filePath = "D:/caiji/"+fileName+"/"; //保存目錄
//
// File file = saveUrlAs(photoUrl, filePath ,"GET");
// }
/**
* 生成6位隨機字符串
* @return
*/
public static String getRandomStr() {
int length = 6;
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static File saveUrlAs(String url,String filePath,String method){
//System.out.println("fileName---->"+filePath);
//創建不同的文件夾目錄
File file=new File(filePath);
//判斷文件夾是否存在
if (!file.exists())
{
//如果文件夾不存在,則創建新的的文件夾
file.mkdirs();
}
FileOutputStream fileOut = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try
{
// 建立鏈接
URL httpUrl=new URL(url);
conn=(HttpURLConnection) httpUrl.openConnection();
//以Post方式提交表單,默認get方式
conn.setRequestMethod(method);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setDoInput(true);
conn.setDoOutput(true);
// post方式不能使用緩存
conn.setUseCaches(false);
//連接指定的資源
conn.connect();
//獲取網絡輸入流
inputStream=conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
//判斷文件的保存路徑后面是否以/結尾
// if (!filePath.endsWith("/")) {
//
// filePath += "/";
//
// }
//寫入到文件(注意文件保存路徑的后面一定要加上文件的名稱)
fileOut = new FileOutputStream(filePath+getRandomStr()+".pdf");
BufferedOutputStream bos = new BufferedOutputStream(fileOut);

byte[] buf = new byte[4096];
int length = bis.read(buf);
//保存文件
while(length != -1)
{
bos.write(buf, 0, length);
length = bis.read(buf);
}
bos.close();
bis.close();
conn.disconnect();
} catch (Exception e)
{
e.printStackTrace();
System.out.println("拋出異常!!");
}

return file;

}

 

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM