Android downloads files over the network in two steps:
1. Establish a network connection to obtain data streams;
2. Create a file and write the data stream to the file. (Simple)
Not much nonsense.Code:
Network processing class httpdownloader. Java
Import java. Io. bufferedreader;
Import java. Io. file;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. inputstreamreader;
Import java.net. httpurlconnection;
Import java.net. malformedurlexception;
Import java.net. url;
/***
* Download an object over HTTP
****/
Public class httpdownloader {
Private URL url = NULL; arrears
Public inputstream getinputstreamformurl (string urlstr)
Throws malformedurlexception, ioexception {
Url = new URL (urlstr );
Httpurlconnection httpc = (httpurlconnection) URL. openconnection ();
Return httpc. getinputstream ();
}
Public String downloadtext (string urlstr ){
Stringbuffer sb = new stringbuffer ();
String line = NULL;
Bufferedreader breader = NULL;
Try {
Url = new URL (urlstr );
Httpurlconnection httpc = (httpurlconnection) URL. openconnection ();
Inputstream inputs = httpc. getinputstream ();
Breader = new bufferedreader (New inputstreamreader (inputs ));
While (line = breader. Readline ())! = NULL ){
SB. append (line );
}
} Catch (exception e ){
E. printstacktrace ();
} Finally {
Try {
Breader. Close ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
Return sb. tostring ();
}
Public int downloadfile (string urlstr, string path, string name ){
Inputstream input = NULL;
Try {
Fileutils Fu = new fileutils ();
If (Fu. isfileexist (path + name) {// whether a file exists. If yes, 1 is returned.
Return 1;
} Else {
Input = getinputstreamformurl (urlstr );
File F = Fu. inputstream2file (path, name, input); Software Development
If (F = NULL ){
Return-1; // return-1 if the data has an exception
}
Input. Close ();
}
} Catch (exception e ){
E. printstacktrace ();
Return-1;
}
Return 0; // return 0 when data is normal
}
}