这个肯定不对,这个是用来下载html文件的,我用了一下,图片下的大部分内容一样,可是稍微有不同
请高手帮忙改一下,先谢了import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;/*
 * Created on 2005-7-20
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 *//**
 * @author 快乐至上
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class ReadGif { public static void getGif() throws Exception {

String URLName = "http://www.baidu.com/img/logo.gif";
int HttpResult;  
URL url=new URL(URLName);  
URLConnection urlconn=url.openConnection();  
urlconn.connect();  
HttpURLConnection httpconn=(HttpURLConnection)urlconn;  
HttpResult=httpconn.getResponseCode();  
System.out.println("ResponseCode: " + httpconn.getResponseCode());
System.out.println("ResponseMessage: " + httpconn.getResponseMessage());
//System.out.println("server: " + httpconn.get);
System.out.println("Date: " + new Date(httpconn.getDate()));
System.out.println("Expiration: " + new Date(httpconn.getExpiration()));
System.out.println("LastModified: " + new Date(httpconn.getLastModified()));
System.out.println("Content-Length: " + httpconn.getContentLength());
System.out.println("Content-Type: " + httpconn.getContentType());

if(HttpResult!=HttpURLConnection.HTTP_OK)  
{  
System.out.println("cant connct0");  
}  
else  
{  
int filesize=urlconn.getContentLength();  
InputStreamReader isReader=new InputStreamReader(urlconn.getInputStream());  
char[] buffer=new char[filesize];
int num=0;  
PrintWriter fileOut = new PrintWriter(new FileWriter("1.gif")); 
String temp = "";
//while(num>-1){  

num=isReader.read(buffer);  
//if(num<0)break; 
try {
fileOut.write(buffer, 0, num);
} catch (Exception e) {
System.out.println(e);
}
fileOut.close();

//}  

isReader.close();
}
} public static void main(String[] args) { try {
ReadGif.getGif();
} catch (Exception e) { } }}

解决方案 »

  1.   

    char[] buffer=new char[filesize];
    int num=0;  
    PrintWriter fileOut = new PrintWriter(new FileWriter("1.gif")); 
    String temp = "";
    //while(num>-1){  

    num=isReader.read(buffer);  
    //if(num<0)break; 
    try {
    fileOut.write(buffer, 0, num);
    } catch (Exception e) {
    System.out.println(e);
    }
    fileOut.close();

    //} 
    改成: int num=0;
    FileOutputStream fileOut = new FileOutputStream("1.gif"); 
    while((num=isReader.read())!=-1) fileOut.write(num);
      

  2.   

    为什么不对?是因为下载下来的图片无法打开吗?如果是的话,我看一下你的代码,就只发现一个地方有问题.网页是文本格式,而图片是二近制流格式,你必须用二近制流写入.也就是:
    DataOutputStream out = new DataOutputStream(new FileOutputStream(path));