public class Download extends Activity {
Button dlTxtButton = null;
Button dlMp3Button = null;
OnClickListener DownloadTxtListener = null;
OnClickListener DownloadMp3Listener = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dlTxtButton = (Button)findViewById(R.id.dlTxtButton);
DownloadTxtListener = new OnClickListener(){
@Override
public void onClick(View v) {
HttpDownloader httpDownloader = new HttpDownloader();
String lrc = httpDownloader.downloadTxt("http://localhost:80/wang/mylove.txt");
System.out.println(lrc);
}
};
dlTxtButton.setOnClickListener(DownloadTxtListener);
dlMp3Button = (Button)findViewById(R.id.dlMp3Button);
DownloadMp3Listener = new OnClickListener(){
@Override
public void onClick(View v) {
HttpDownloader httpDownloader = new HttpDownloader();
int result = httpDownloader.downloadFile("http://localhost:80/wang/mylove.mp3","mylove/","mylove.mp3");
System.out.println(result);
}
};
dlMp3Button.setOnClickListener(DownloadMp3Listener);
}
}
public class HttpDownloader {
private URL url = null;
/*****根据URL下载文件,前提是这个文件当中的内容是文本,函数返回的是文本文件的内容****/
/*1.创建一个URL对象
2.通过URL对象,创建一个HttpURLConnection对象
3.通过urlConn.getInputStream()方法得到InputStream输入流
4.从InputStream中读取数据
*/
public String downloadTxt(String urlStr){
StringBuffer sb = new StringBuffer();//创建一个具有16个字符缓冲区的空字符串
String line = null;
BufferedReader buffer = null;
try {
//创建一个URL对象
url = new URL(urlStr);
//创建一个http连接对象
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//使用io读取数据
buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
//urlConn.getInputStream()得到一个输入流,代表在这个地址下载的文本文件
while((line = buffer.readLine()) != null)
{
sb.append(line);//在空字符串后面追加字符串数据
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
buffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return sb.toString();
}
/****创建任意形式的文件
*该函数返回整形
*返回-1,代表下载文件出错
*返回0,代表下载文件成功
*返回1,代表下载文件已存在
****/
public int downloadFile(String urlStr,String path,String fileName)//urlStr是传递网络中的地址
{
InputStream inputStream = null;
//创建FileUtils对象
try {
FileUtils fileUtils = new FileUtils();
if(fileUtils.isFileExit(path + fileName))
{
return 1;
}else{
inputStream = getInputStreamFromUrl(urlStr);
//调用writeToSDFromInput方法:创建一个目录,并且在这个目录下创建文件
File resultFile = fileUtils.writeToSDFromInput(path, fileName, inputStream);
if(resultFile == null){
return -1;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -1;
}finally{
try {
inputStream.close();
} catch (IOException e) {