import java.io.*;
import java.net.HttpURLConnection;
/**
* 网络文件存取类
*
* @author GamVan by 我容易么我
*/
public class FileOperate {
public FileOperate() {
}
/**
* 如果远程文件读取失败用此文件替代
*/
public String readerr = "";
/**
* 收集运行哪个结果或错误信息
*/
public String message = "";
/**
* 根据文件url地址采集并创建到本地
*
* @param fileUrl 文件url路径
* @param filePathAndName 预创建到本地的文件的绝对路径含文件名已经扩展名
* @return
* @throws IOException 2006-1-17 4:48:06 made in GamVan
*/
public boolean createFile(String fileUrl, String filePathAndName) throws IOException
{
boolean bea = false;
java.net.URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File f = new File(filePathAndName);
try {
//连接指定的网络资源,获取网络输入流
urlfile = new java.net.URL(fileUrl);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
} catch (Exception e) {
if (readerr != null && !readerr.equals("")) {
try {
urlfile = new java.net.URL(readerr);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
} catch (Exception e1) {
message = e1.toString();
}
}
message = e.toString();
}
try {
bos =
new BufferedOutputStream(new FileOutputStream(f));
;
byte[] b = new byte[1024];
while (bis.read(b) != -1)
{
bos.write(b);
}
bea = true;
message = fileUrl + " 采集成功!文件已存储至:" + filePathAndName;
} catch (Exception e) {
bea = false;
message = e.toString();
} finally {
try {
bos.flush();
bis.close();
httpUrl.disconnect();
} catch (Exception e) {
message = e.toString();
}
}
return bea;
}
public void setReaderr(String readerr) {
this.readerr = readerr;
}
public String getMessage() {
return this.message;
}
/* test */
public static void main(String args[]) {
//远程文件路径
String s1 = "http://club.gamvan.com/club/GVimgs/mainLogo.gif";
//本地存放路径
String s2 = "E://MYJAVA//1.jpg";
try {
FileOperate fo = new FileOperate();
fo.setReaderr("http://club.gamvan.com/club/GVimgs/mainLogo.gif");
fo.createFile(s1, s2);
System.out.println(fo.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
}