0

Usually I use this code to download a file :

Server:

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

Client:

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

And it works, ok, but I was wondering if there was a direct way to download the file from the server.

EDIT: Now I'm trying to use this cose, but i get a ConnectionException

Server side:

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

Client side:

        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);

It's possible to do something like this?

M3M3X
  • 31
  • 1
  • 6
  • 2
    What do you mean by direct, and how is what you've got not direct? – gvlasov Feb 28 '15 at 17:03
  • http://stackoverflow.com/a/24041297/1393766 – Pshemo Feb 28 '15 at 19:06
  • I mean not to have the server read the file. Maybe it is possible to send the URI of the file to the client? – M3M3X Feb 28 '15 at 22:13
  • I want to clarify the context: we have a file on machine A and machine B wants to download it. There is a way to prevent the machine A reads the file to be sent to B? – M3M3X Feb 28 '15 at 22:40
  • I'm trying to use the URI of the file to download it, but it seems to be inaccesible from remote; maybe the NAT block the access? the URI that I use is like this: file://MYIP/C:/Users/user/Desktop/test.jpg . It's possible to do something like this? – M3M3X Mar 01 '15 at 12:12
  • I was reading the smb protocol ... could be useful for my purpose? – M3M3X Mar 01 '15 at 22:15

1 Answers1

0

You're using files in you server-client communication, for direct aproach you need to make use of sockets. You can always include 3rd party libraries for this task, like for example ApacheHttpComponents. Hope I helped you a bit.

Trynkiewicz Mariusz
  • 2,722
  • 3
  • 21
  • 27
  • The stream that I used already comes from the socket... I was thinking if it is possible to use a URI directly to the file on the server without using the FileInputStream to read it. – M3M3X Feb 28 '15 at 22:35