请问各位大哥,我现在正在做一个功能,就是怎么从服务器那里下载文件到本地? 希望给出代码 小弟非常感谢!

解决方案 »

  1.   

    直接把要下载的文件的路径插入数据库中,路径是WEB应用的相对路径噢!然后在取这个文件的记录的时候,就可以通过HTTP协议进行下载了
      

  2.   

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.URL;
    import java.util.ArrayList;public class URLDownloadFiles { private String _desRoot = null;
    private String _locRoot = null;
    private ArrayList<URL> _listURL = null;
    private ArrayList<File> _listFile = null;
    private final int _buffSize = 512;

    public URLDownloadFiles (String desRoot, String locRoot) {
    this._desRoot = desRoot;
    this._locRoot = locRoot;
    inti();
    }

    /*
         * inti
         */
    private void inti() {
    _listURL = new ArrayList<URL>();
    _listFile = new ArrayList<File>();
    // Get all files' URL and files' list
    if (!getFiles(_desRoot, _listFile, _listURL)) {
    return;
    }
    // copy the dest files to local files
    copyFiles();
    }


    /*
         * @param desRoot 
         * @param listFile 
         * @param listURL 
         */
    private boolean getFiles(String desRoot, ArrayList<File>listFile, ArrayList<URL> listURL) {
    File[] fileList = null;
    URL[] urlList = null;
    File desRootFile = new File(desRoot);
    try {
    // desRootFile does not exist
    if (!desRootFile.exists()) {
    System.out.println("DesRoot does not exist");
    return false;

    // desRootFile exist
    else {
    // desRootFile is not a directory
    if (!desRootFile.isDirectory()) {
    System.out.println("This is not a directory!");
    if (!desRootFile.isFile()) {
    System.out.println("This is not a file too! Plz chk the root!");
    return false;
    } else {
    System.out.println("This is a file!");
    return false;
    }

    // desRootFile is a directory, get all sub files and folders
    else {
    fileList = desRootFile.listFiles();
    urlList = new URL[fileList.length];
    for (int i = 0; i < fileList.length; i++) {
    if (fileList[i].isDirectory()) {
    listFile.add(fileList[i]);
    urlList[i] = new URL("file:" + fileList[i].getPath());
    listURL.add(urlList[i]);
    // get sub folders
    getFiles(fileList[i].getPath(), listFile, listURL);
    } else {
    listFile.add(fileList[i]);
    urlList[i] = new URL("file:" + fileList[i].getPath());
    listURL.add(urlList[i]);
    }
    }
    }
    }
    } catch (IOException e) {
    System.out.println(e);
    return false;
    } catch (Exception e) {
    System.out.println(e);
    return false;
    }
    return true;
    }

    /*
         */
    private boolean copyFiles() {
    File dir, locFile;
    BufferedInputStream buffIn = null;
    BufferedOutputStream buffOut = null;
    dir = new File(_locRoot);
    try {
    // dir doesn't exist
    if (!dir.exists()) {
    //create dir
    dir.mkdir();
    //copy new files
    for (int i = 0; i < _listFile.size(); i++) {
    if (_listFile.get(i).isDirectory()) {
    System.out.println(_listFile.get(i) + " isDirectory");
    continue;
    } else {
    locFile = new File(dir, _listFile.get(i).getName());
    buffIn = new BufferedInputStream(_listURL.get(i).openStream());
    buffOut = new BufferedOutputStream(new FileOutputStream(locFile));
    byte buffer[] = new byte[_buffSize];
    int count = _buffSize;
    while ((count = buffIn.read(buffer)) != -1) {
    buffOut.write(buffer, 0, count);
    }
    buffOut.flush();
    buffIn.close();
    buffOut.close();
    buffIn = null;
    buffOut = null;
    }
    }

    // dir exist
    else { 
    // delete old files
    File[] files = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
    files[i].delete();
    }
    // copy new files
    for (int i = 0; i < _listFile.size(); i++) {
    if (_listFile.get(i).isDirectory()) {
    System.out.println(_listFile.get(i) + " isDirectory");
    continue;
    } else {
    locFile = new File(dir, _listFile.get(i).getName());
    buffIn = new BufferedInputStream(_listURL.get(i).openStream());
    buffOut = new BufferedOutputStream(new FileOutputStream(locFile));
    byte buffer[] = new byte[_buffSize];
    int count = _buffSize;
    while ((count = buffIn.read(buffer)) != -1) {
    buffOut.write(buffer, 0, count);
    }
    buffOut.flush();
    buffIn.close();
    buffOut.close();
    buffIn = null;
    buffOut = null;
    }
    }
    }
    } catch (IOException e) {
    System.out.println(e);
    return false;
    } catch (Exception e) {
    System.out.println(e);
    return false;
    }
    return true;
    }
    /**
     * @param args temp
     */
    public static void main(String[] args) {
    String desRoot = "\\\\192.168.1.153\\api\\allclasses-noframe.html";
    // String desRoot = "\\E:\\api";
    String locRoot = "\\E:\\api copy";
    URLDownloadFiles test = new URLDownloadFiles(desRoot, locRoot);
    // test
    for (int i = 0; i < test._listFile.size(); i++) {
    if (!test._listFile.get(i).isDirectory()) {
    System.out.println(test._listFile.get(i));
    System.out.println(test._listURL.get(i));
    }
    }
    }}
      

  3.   

    楼上这种方法最简单,不用特别的写其它代码;
    如果楼主对文件下载有权限控制,或者文件想放在浏览器不能访问的地方,如:/WEB-INF/下面,可以自己写一个servlet来读取文件,然后再输出到输出流中;
      

  4.   

    1.得到客户端文件流对象
    2.设置客户端文件类型
    3.将流写到本地目录
    public void writeResponse(
    FileInputStream is,
    HttpServletResponse res,
    String fileName) {
    try {
                               //取扩展名
    String fileExt = getFileExt(fileName);
                              //得到文件类型 
                              String contentType = getContentType(fileExt);

    res.setContentType(contentType);
    fileName = new String(fileName.getBytes("GB2312"), "ISO-8859-1");
    ServletOutputStream out = res.getOutputStream();
    String contentHeader = "attachment; filename=\"" + fileName + "\"";
    res.setHeader("Content-disposition", contentHeader);
    int MAX_FILE_SIZE = 3 * 1024 * 1024; //3M
    byte[] buffer = new byte[MAX_FILE_SIZE];
             int length = 0;
    while ((length = is.read(buffer)) != -1) {
       out.write(buffer, 0, length);
    }
    if (is != null) is.close();
    if (out != null)out.close();

             catch (Exception e) 
            {
    System.out.println("writeResponse error");
    }
    }
    //获得内容类型
    private String getContentType(String fileExt) {
    String contentType = "";
    if (fileExt == null)
    contentType = "";
    else if (fileExt.equals("doc"))
    contentType = "application/msword";
    else if (fileExt.equals("pdf"))
    contentType = "application/pdf";
    else if (fileExt.equals("jpg"))
    contentType = "image/jpeg";
    else if (fileExt.equals("gif"))
    contentType = "image/gif";
    else if (fileExt.equals("bmp"))
    contentType = "image/bmp";
    else if (fileExt.equals("txt"))
    contentType = "text/plain"; return contentType;
    }
      

  5.   

    http本身就可以下载文件,有必要自己搞吗?楼主也没有说出必须自己搞的理由。