java:如何直接下载文件?

时间:2015-02-28 16:57:00

标签: java file download

通常我使用此代码下载文件:

服务器:

        FileInputStream fin = new FileInputStream(file);
        long length = file.length();
        out.writeLong(length);
        out.flush();
        while (length > 0) {
            out.writeByte(fin.read());
            out.flush();
            length--;
        }

客户端:

       FileOutputStream fout = new FileOutputStream(downloaded);
       long length = in.readLong();
       while (length > 0) {
            Byte next = (Byte) in.readByte();
            fout.write(next);
            length--;
       }

它确实有效,但我想知道是否有直接从服务器下载文件的方法。

编辑: 现在我正在尝试使用这个cose,但我得到了一个ConnectionException

服务器端:

        URI uri = file.toURI();
        uri = setHost(uri, getMyIPAddress());
        System.out.println("URI: " + uri);
        out.writeObject(uri);

客户方:

        File downloaded = new File("downloaded");
        downloaded.createNewFile();
        URI uri = (URI) in.readObject();
        URL url = uri.toURL();
        Files.copy(url.openConnection().getInputStream(),downloaded.toPath(),StandardCopyOption.REPLACE_EXISTING);

可以做这样的事情吗?

1 个答案:

答案 0 :(得分:0)

您正在使用服务器 - 客户端通信中的文件,直接需要make use of sockets。您始终可以为此任务包含第三方库,例如ApacheHttpComponents。希望我能帮助你一点。

相关问题