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?