我这是从tomcat的一个目录里得到一个流,然后下载到本地..但是如果我要下载具体的一个文件该怎么办啊..那个fileName该增加到哪里.
public void read(String filePath,String fileName) { 
try { 
URL ur = new URL("http://localhost:8080/ftpdowns/MyServlet"); 
HttpURLConnection conn = (HttpURLConnection) ur.openConnection(); 
conn.connect(); 
InputStream is = conn.getInputStream(); 
OutputStream os = new FileOutputStream(filePath); 
byte[] bs = new byte[1024]; 
int len; 
while ((len = is.read(bs)) != -1) { 
os.write(bs, 0, len); 

} catch (MalformedURLException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 

}

解决方案 »

  1.   


    import java.net.*;
    import java.io.*;public class Test{
    public static void main(String[] args){
    new Test().read("D:/baidu.html");

    } public void read(String fileName) { 
    try { 
    URL ur = new URL("http://www.baidu.com:80/"); 
    HttpURLConnection conn = (HttpURLConnection) ur.openConnection(); 
    conn.connect(); 
    InputStream is = conn.getInputStream(); 
    OutputStream os = new FileOutputStream(fileName); 
    byte[] bs = new byte[1024]; 
    int len; 
    while ((len = is.read(bs)) != -1) { 
    os.write(bs, 0, len); 

    } catch (MalformedURLException e) { 
    e.printStackTrace(); 
    } catch (IOException e) { 
    e.printStackTrace(); 

    }
    };
      

  2.   

    如果你你读取的是html的文件建议使用字符流读取InputStreamReader isr=new InputStreamReader(is);
    BufferedReader br=new BufferedReader(isr);
    FileOutputStream fos=new FileOutputStream("D:/baidu.html");
    while((strLine=br.readLine())!=null)
    {
    fos.write(strLine.getBytes());
    }如果图片之类的\n也属于文件一部分的InputStreamReader isr=new InputStreamReader(is);
    FileOutputStream fos=new FileOutputStream("D:/baidu.html");
    while((strLine=br.readLine())!=null)
    int data;
    while((data=is.read())!=-1)
    {
    fos.write(data);
    }
      

  3.   

    晕,错了!
    应该是:
    如果你你读取的是图像的文件建议使用字节流读取 InputStream is=urlConn.getInputStream();
    FileOutputStream fos=new FileOutputStream("D:\\2.gif");
    int data;
    while((data=is.read())!=-1)
    {
    fos.write(data);
    }
    如果是html的文件InputStream is=urlConn.getInputStream();
    InputStreamReader isr=new InputStreamReader(is);
    BufferedReader br=new BufferedReader(isr);
    FileOutputStream fos=new FileOutputStream("2.html");
    String strLine;
    while((strLine=br.readLine())!=null)
    {
    fos.write(strLine.getBytes());}