urlでファイルをローカルにダウンロード
3352 ワード
1:URLでファイルをダウンロードする:
2:バッファ読み込みURLメソッド:
-----------------------------------------------------------
public class DownFile {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String encodedStr = java.net.URLEncoder.encode(" ","GBK"); // UTF-8
download("http://www.baidu.com?args=" + encodedStr,"c:\\ret.html");
download("http://music.yule.sohu.com/upload/zhiqianqiutian.mp3", "C:\\1.mp3");
}
public static void download(String urlString,String filename)throws Exception{
URL url = new URL(urlString);
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
byte[] bs = new byte[1024];
int len;
OutputStream os = new FileOutputStream(filename);
while((len = is.read(bs))!=-1){
os.write(bs, 0, len);
}
os.close();
is.close();
}
}
2:バッファ読み込みURLメソッド:
package com.rayoo.test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class TestDownFile {
public static void main(String[] args) throws Exception {
java.net.URLDecoder.decode(java.net.URLEncoder.encode(" ", "GBK"), "GBK");
download("http://music.yule.sohu.com/upload/zhiqianqiutian.mp3", "C:\\1.mp3");
}
public static void download(String urlString, String filename)
throws Exception {
URL url = new URL(urlString);
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
OutputStream os = new FileOutputStream(filename);
BufferedInputStream bufferInput = new BufferedInputStream(is);
BufferedOutputStream bufferOutput = new BufferedOutputStream(os);
byte[] bs = new byte[1024];
int len = 0;
while ((len = bufferInput.read(bs)) != -1) {
bufferOutput.write(bs, 0, len);
}
bufferOutput.flush();
bufferInput.close();
bufferOutput.close();
os.close();
is.close();
}
}
-----------------------------------------------------------
URL url = new URL("http://www.baidu.com");
InputStream is = url.openStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final byte[] bytes = new byte[1024];
int read = 0;
while ((read = is.read(bytes)) >= 0) {
byteArrayOutputStream.write(bytes, 0, read);
}
File file = new File("c:\\test.txt");
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
if(!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write(byteArrayOutputStream.toByteArray());
is.close();
fos.close();