|
Java 实现这个功能非常简单,就是建立一个URL 然后进行操作就可以了。 以下是简单的程序代码,没有要求从控制太输入url。
import java.net.*; import java.io.*; /** 从网上下载二进制文件存到本地 FileName:BinarySaver.java @Author:Alec Cheung MSN:eboysit@hotmail.com Date:2003-5-21 Home:http://cheung.cxc.cc http://www.andyfans.com http://97741.126.com Oicq:1695925 */
public class BinarySaver {
public static void main(String args[]){ try{ URL root = new URL("http://localhost:8888/97741/images/title.jpg"); saveBinaryFile(root); } catch(IOException e){ System.err.println(e); } } //end main
public static void saveBinaryFile(URL u) throws IOException{ URLConnection uc = u.openConnection(); String contentType = uc.getContentType(); int contentLength = uc.getContentLength();
if (contentType.startsWith("text/") || (contentLength == -1)) { throw new IOException("this is not a binary file."); }
InputStream raw = uc.getInputStream(); InputStream in = new BufferedInputStream(raw); byte[] data = new byte[contentLength]; int bytesRead = 0; int offset = 0; while (offset < contentLength) { bytesRead = in.read(data,offset,data.length-offset); if(bytesRead == -1) break; offset +=bytesRead; } in.close();
if (offset != contentLength) { throw new IOException("Only read "+offset+" bytes;Expected "+contentLength+" bytes."); }
String fileName = u.getFile(); String filePath = "D:\java\"; fileName = fileName.substring(fileName.lastIndexOf('/')+1); FileOutputStream fout = new FileOutputStream(filePath+fileName); fout.write(data); fout.flush(); fout.close(); } }
|