java-どのようにURLによってネットワークからリソースをダウンロードしますか?
仕事の中で7万件近くのURLがあるリンクに出会いました。写真をダウンロードして確認する必要があります。具体的なコードは以下の通りです。
1.ネットワークのURLからリソースを取得する方法
1.ネットワークのURLからリソースを取得する方法
/**
* Url
* @param urlStr
* @param fileName
* @param savePath
* @throws IOException
*/
public static void downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
// 3
conn.setConnectTimeout(3*1000);
// 403
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//
InputStream inputStream = conn.getInputStream();
//
byte[] getData = readInputStream(inputStream);
//
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
System.out.println("info:"+url+" download success");
}
/**
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
2.ファイルからURLを読み取って操作する方法// url
File file=new File("C:\\Users\\yejianan\\Desktop\\chuanda.txt");
BufferedReader reader=null;
String temp=null;
int line=1;
PrintWriter pw = null;
try{
reader=new BufferedReader(new FileReader(file));
while((temp=reader.readLine())!=null){
// url
//int index=temp.indexOf('h');
//String res=temp.substring(index);//res url
System.out.println("line"+line+":"+temp);
try{
downLoadFromUrl(temp,line+".jpg","C:\\Users\\yejianan\\Desktop\\chuanda");
}catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
line++;
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(reader!=null){
try{
reader.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
この部分の仕事は実はリンクをつけてから見る作業量を軽減するために、直接コードを通して画像のダウンロードを行い、直接検査とマークを行います。