java中的文件未正确下载

时间:2012-11-07 19:53:37

标签: java web-applications web

我想将文件从服务器下载到客户端计算机。但我希望从浏览器下载文件:我希望将文件保存在下载文件夹中。

我使用以下代码下载文件。

public void descarga(String address, String localFileName) {

OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
    // Get the URL
    URL url = new URL(address);
    // Open an output stream to the destination file on our local filesystem

    out = new BufferedOutputStream(new FileOutputStream(localFileName));
    conn = url.openConnection();
    in = conn.getInputStream();

    // Get the data
    byte[] buffer = new byte[1024];
    int numRead;
    while ((numRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, numRead);
    }
    // Done! Just clean up and get out
} catch (Exception exception) {
    exception.printStackTrace();
} finally {
    try {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    } catch (IOException ioe) {
        // Shouldn't happen, maybe add some logging here if you are not
        // fooling around ;)
    }
    }

它可以工作,但除非我指定绝对路径它不下载文件,因此从使用不同浏览器的不同客户端无用,因为网页甚至没有提示让用户知道文件正在存在的消息下载。我可以添加什么才能让它发挥作用?

由于

0 个答案:

没有答案