import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* @{#} Test.java Create on Mar 5, 2010 10:21:24 AM
*
* Copyright (c) 2010 by shilm.
* @author <a href="mailto:feizaisky@gmail.com">shilm</a>
* @version 1.0
*/
public class Test {
public static void main(String[] args) {
String str = getFileFromURL("http://blog.shilimin.com/wp-content/gallery/talou/dsc_0284.jpg", "E://data//image//", "dsc_0284.jpg");
System.out.println(str);
}
/**
* @param urlString
* 文件网络地址
* @param fileDir
* 本地存储目录
* @param fileName
* 本地存储文件名
* @return 文件在本地存储的全路径
*/
public static String getFileFromURL(String urlString, String fileDir, String fileName) {
String filePath = fileDir + fileName;
File dirPath = new File(fileDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
InputStream is = null;
OutputStream os = null;
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
is = conn.getInputStream();
os = new FileOutputStream(filePath);
byte[] b = new byte[512];
int len = 0;
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
;
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
;
}
}
}
return filePath;
}
}