开发者

How to download a file from a server

开发者 https://www.devze.com 2023-01-29 07:25 出处:网络
I have a question with a general design implementation. Hope anyone more skilled than me helps me. I want to do an application based on an android client and a java server. Local wifi transmission, n

I have a question with a general design implementation. Hope anyone more skilled than me helps me.

I want to do an application based on an android client and a java server. Local wifi transmission, no 3G.

Basically, the client must connect to the server and request 开发者_StackOverflowa file to download using a code.

How can I do that?

Things I know:

  • I must create a background thread in the client to create a file in the SD card and update a progress bar using a Handler to communicate with the UI thread.

  • The server must be multithread and non-blocking.

  • The file is a binary file like a mp3 audio. So the server has to:

    1. Send information about the file: name and total length.
    2. Open the file, read and send bytes while it does not reach the end.

  • The client has to:

    1. Receive the information about the file and create an empty file.
    2. Read bytes and dump them into the empty file. Update progress bar.
    3. When all bytes are recieved close the file.

I have knowledge implementing a client and server in C (very awful) but I am beginning with a real client-server application done in java.

Questions:

  • How can I download a binary file like an mp3 from a server to a client?

  • Where I have to put my server application? I supose that I must create a jar, save it on a folder and execute it at PC start-up, right?

Thanks!


How can I download a binary file like an mp3 from a server to a client?

To download a file with Java, you can Use URL.openStream();

http://download.oracle.com/javase/tutorial/networking/urls/readingURL.html

Don't print the output to System.out. Write it to a file, instead.

FileOutputStream fos = new FileOutputStreamm(new File("path_to_file.mp3");
int byte;

while ((byte= in.readLine()) != -1)
    fos.write(byte);

Where I have to put my server application? Don't implement a server unless you really have to. Use an http-Server if possile (Tomcat oder Apache HTTPD). Make your file available through HTTP.

If you want to use a Java Server, you should write a Servlet and packkage it into a WAR-File:

http://docstore.mik.ua/orelly/java-ent/servlet/

0

精彩评论

暂无评论...
验证码 换一张
取 消