android开发 音乐,文件下载

今天和大家分享一下在android上怎么下载文件到手机上。

主要有两点大类容:

一,通过Http协议下载文件。

创建一个HttpURLConnection对象

  1. HttpURLConnection urlConn = (HttpURLConnection) url  
  2.      .openConnection();  
HttpURLConnection urlConn = (HttpURLConnection) url
     .openConnection();

 获得一个InputStream对象

  1. inputStream = urlConn.getInputStream();  
inputStream = urlConn.getInputStream();

访问网络的权限

  1. <uses-permission android:name="android.permission.INTERNET"/>  
<uses-permission android:name="android.permission.INTERNET"/>



二,将下载的文件写入SDcard。

得到当前设备的SD卡目录

  1. Environment.getExternalStorageDirectory()  
Environment.getExternalStorageDirectory()

设置访问SD卡的权限

  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


下面给出具体的代码:

DownLoad.java

  1. import android.app.Activity;  
  2. import android.os.Bundle;  
  3. import android.util.HttpDownloader;  
  4. import android.view.View;  
  5. import android.view.View.OnClickListener;  
  6. import android.widget.Button;  
  7.   
  8. public class DownLoad extends Activity {  
  9.     private Button textButton;  
  10.     private Button audioButton;  
  11.   
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);  
  16.         //文本下载   
  17.         textButton = (Button) findViewById(R.id.textButton);  
  18.         textButton.setOnClickListener(new OnClickListener() {  
  19.   
  20.             @Override  
  21.             public void onClick(View v) {  
  22.                 HttpDownloader http = new HttpDownloader();  
  23.                 //注意这里不要用localhost或者127.0.0.1,会报错的,因为android里是10.0.2.2   
  24.                 String txt = http  
  25.                         .download("http://10.0.2.2:8080/examples/123123.txt");  
  26.                 System.out.println(txt);  
  27.             }  
  28.         });  
  29.         //音频下载   
  30.         audioButton = (Button) findViewById(R.id.audioButton);  
  31.         audioButton.setOnClickListener(new OnClickListener() {  
  32.   
  33.             @Override  
  34.             public void onClick(View v) {  
  35.                 HttpDownloader http = new HttpDownloader();  
  36.                 String result = http.download(  
  37.                         "http://10.0.2.2:8080/examples/123.mp3""/music",  
  38.                         "zhou.mp3");  
  39.                 System.out.println(result);  
  40.             }  
  41.         });  
  42.   
  43.     }  
  44. }  
import android.app.Activity;
import android.os.Bundle;
import android.util.HttpDownloader;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DownLoad extends Activity {
	private Button textButton;
	private Button audioButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//文本下载
		textButton = (Button) findViewById(R.id.textButton);
		textButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				HttpDownloader http = new HttpDownloader();
				//注意这里不要用localhost或者127.0.0.1,会报错的,因为android里是10.0.2.2
				String txt = http
						.download("http://10.0.2.2:8080/examples/123123.txt");
				System.out.println(txt);
			}
		});
		//音频下载
		audioButton = (Button) findViewById(R.id.audioButton);
		audioButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				HttpDownloader http = new HttpDownloader();
				String result = http.download(
						"http://10.0.2.2:8080/examples/123.mp3", "/music",
						"zhou.mp3");
				System.out.println(result);
			}
		});

	}
}

FileUtil.java

  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6.   
  7. import android.os.Environment;  
  8.   
  9. public class FileUtil {  
  10.     private String SDCARDPATH;  
  11.   
  12.     public String getSDCARDPATH() {  
  13.         return SDCARDPATH;  
  14.     }  
  15.   
  16.     public FileUtil() {  
  17.         // 得到手机存储器目录---因为各个厂商的手机SDcard可能不一样,最好不要写死了   
  18.         SDCARDPATH = Environment.getExternalStorageDirectory() + "/";  
  19.     }  
  20.   
  21.     /** 
  22.      * 在SDcard上创建文件 
  23.      *  
  24.      * @param fileName 
  25.      * @return File 
  26.      */  
  27.     public File creatSDFile(String fileName) {  
  28.         File file = new File(SDCARDPATH + fileName);  
  29.         return file;  
  30.     }  
  31.   
  32.     /** 
  33.      * 在SDcard上创建目录 
  34.      *  
  35.      * @param dirName 
  36.      */  
  37.     public void createSDDir(String dirName) {  
  38.         File file = new File(SDCARDPATH + dirName);  
  39.         file.mkdir();  
  40.     }  
  41.   
  42.     /** 
  43.      * 判断文件是否存在 
  44.      *  
  45.      * @param fileName 
  46.      * @return boolean 
  47.      */  
  48.     public boolean isFileExist(String fileName) {  
  49.         File file = new File(SDCARDPATH + fileName);  
  50.         return file.exists();  
  51.     }  
  52.   
  53.     /** 
  54.      * @param path 
  55.      *            存放目录 
  56.      * @param fileName 
  57.      *            文件名字 
  58.      * @param input 
  59.      *            数据来源 
  60.      * @return 
  61.      */  
  62.     public File writeToSDCard(String path, String fileName, InputStream input) {  
  63.         File file = null;  
  64.         OutputStream output = null;  
  65.         try {  
  66.             //创建路径   
  67.             createSDDir(path);  
  68.             //创建文件   
  69.             file = creatSDFile(path + fileName);  
  70.             output = new FileOutputStream(file);  
  71.             //以4K为单位,每次写4k   
  72.             byte buffer[] = new byte[4 * 1024];  
  73.             while ((input.read(buffer)) != -1) {  
  74.                 output.write(buffer);  
  75.             }  
  76.             // 清除缓存   
  77.             output.flush();  
  78.         } catch (IOException e) {  
  79.             e.printStackTrace();  
  80.         } finally {  
  81.             try {  
  82.                 // 关闭流   
  83.                 output.close();  
  84.             } catch (IOException e) {  
  85.                 e.printStackTrace();  
  86.             }  
  87.         }  
  88.         return file;  
  89.     }  
  90. }  
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtil {
	private String SDCARDPATH;

	public String getSDCARDPATH() {
		return SDCARDPATH;
	}

	public FileUtil() {
		// 得到手机存储器目录---因为各个厂商的手机SDcard可能不一样,最好不要写死了
		SDCARDPATH = Environment.getExternalStorageDirectory() + "/";
	}

	/**
	 * 在SDcard上创建文件
	 * 
	 * @param fileName
	 * @return File
	 */
	public File creatSDFile(String fileName) {
		File file = new File(SDCARDPATH + fileName);
		return file;
	}

	/**
	 * 在SDcard上创建目录
	 * 
	 * @param dirName
	 */
	public void createSDDir(String dirName) {
		File file = new File(SDCARDPATH + dirName);
		file.mkdir();
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param fileName
	 * @return boolean
	 */
	public boolean isFileExist(String fileName) {
		File file = new File(SDCARDPATH + fileName);
		return file.exists();
	}

	/**
	 * @param path
	 *            存放目录
	 * @param fileName
	 *            文件名字
	 * @param input
	 *            数据来源
	 * @return
	 */
	public File writeToSDCard(String path, String fileName, InputStream input) {
		File file = null;
		OutputStream output = null;
		try {
			//创建路径
			createSDDir(path);
			//创建文件
			file = creatSDFile(path + fileName);
			output = new FileOutputStream(file);
			//以4K为单位,每次写4k
			byte buffer[] = new byte[4 * 1024];
			while ((input.read(buffer)) != -1) {
				output.write(buffer);
			}
			// 清除缓存
			output.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}
}

HttpDownloader.java

  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.MalformedURLException;  
  8. import java.net.URL;  
  9.   
  10. public class HttpDownloader {  
  11.     private URL url = null;  
  12.   
  13.     /** 
  14.      * 下载文本文件 
  15.      *  
  16.      * @param urlStr 
  17.      * @return 
  18.      */  
  19.     public String download(String urlStr) {  
  20.         StringBuffer sb = new StringBuffer();  
  21.         String line = null;  
  22.         BufferedReader buffer = null;  
  23.         try {  
  24.             buffer = new BufferedReader(new InputStreamReader(  
  25.                     getInputStreamFromUrl(urlStr)));  
  26.             //一行一行的读取   
  27.             while ((line = buffer.readLine()) != null) {  
  28.                 sb.append(line);  
  29.             }  
  30.         } catch (Exception e) {  
  31.             e.printStackTrace();  
  32.         } finally {  
  33.             try {  
  34.                 buffer.close();  
  35.             } catch (IOException e) {  
  36.                 e.printStackTrace();  
  37.             }  
  38.         }  
  39.         return sb.toString();  
  40.     }  
  41.   
  42.     /** 
  43.      * @param urlStr 
  44.      *            文件所在的网络地址 
  45.      * @param path 
  46.      *            存储的目录 
  47.      * @param fileName 
  48.      *            存放的文件名 
  49.      * @return 状态 
  50.      */  
  51.     public String download(String urlStr, String path, String fileName) {  
  52.         InputStream inputStream = null;  
  53.         try {  
  54.             FileUtil fileUtils = new FileUtil();  
  55.             //判断文件是否已存在   
  56.             if (fileUtils.isFileExist(path + fileName)) {  
  57.                 return "fileExist";  
  58.             } else {  
  59.                 inputStream = getInputStreamFromUrl(urlStr);  
  60.                 File resultFile = fileUtils.writeToSDCard(path, fileName,  
  61.                         inputStream);  
  62.                 //如果resultFile==null则下载失败   
  63.                 if (resultFile == null) {  
  64.                     return "downloadError";  
  65.                 }  
  66.             }  
  67.         } catch (Exception e) {  
  68.             //如果异常了,也下载失败   
  69.             e.printStackTrace();  
  70.             return "downloadError";  
  71.         } finally {  
  72.             try {  
  73.                 //别忘了关闭流   
  74.                 inputStream.close();  
  75.             } catch (IOException e) {  
  76.                 e.printStackTrace();  
  77.             }  
  78.         }  
  79.         return "downloadOk";  
  80.   
  81.     }  
  82.   
  83.     /** 
  84.      * 连接到网络( 抽取的公共方法) 
  85.      *  
  86.      * @param urlStr 
  87.      *            文件所在的网络地址 
  88.      * @return InputStream 
  89.      */  
  90.     public InputStream getInputStreamFromUrl(String urlStr) {  
  91.         InputStream inputStream = null;  
  92.         try {  
  93.             // 创建一个URL对象   
  94.             url = new URL(urlStr);  
  95.             // 根据URL对象创建一个HttpURLConnection连接   
  96.             HttpURLConnection urlConn = (HttpURLConnection) url  
  97.                     .openConnection();  
  98.             // IO流读取数据   
  99.             inputStream = urlConn.getInputStream();  
  100.         } catch (MalformedURLException e) {  
  101.             e.printStackTrace();  
  102.         } catch (IOException e) {  
  103.             e.printStackTrace();  
  104.         }  
  105.         return inputStream;  
  106.     }  
  107.   
  108. }  
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;

public class HttpDownloader {
	private URL url = null;

	/**
	 * 下载文本文件
	 * 
	 * @param urlStr
	 * @return
	 */
	public String download(String urlStr) {
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			buffer = new BufferedReader(new InputStreamReader(
					getInputStreamFromUrl(urlStr)));
			//一行一行的读取
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				buffer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * @param urlStr
	 *            文件所在的网络地址
	 * @param path
	 *            存储的目录
	 * @param fileName
	 *            存放的文件名
	 * @return 状态
	 */
	public String download(String urlStr, String path, String fileName) {
		InputStream inputStream = null;
		try {
			FileUtil fileUtils = new FileUtil();
			//判断文件是否已存在
			if (fileUtils.isFileExist(path + fileName)) {
				return "fileExist";
			} else {
				inputStream = getInputStreamFromUrl(urlStr);
				File resultFile = fileUtils.writeToSDCard(path, fileName,
						inputStream);
				//如果resultFile==null则下载失败
				if (resultFile == null) {
					return "downloadError";
				}
			}
		} catch (Exception e) {
			//如果异常了,也下载失败
			e.printStackTrace();
			return "downloadError";
		} finally {
			try {
				//别忘了关闭流
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "downloadOk";

	}

	/**
	 * 连接到网络( 抽取的公共方法)
	 * 
	 * @param urlStr
	 *            文件所在的网络地址
	 * @return InputStream
	 */
	public InputStream getInputStreamFromUrl(String urlStr) {
		InputStream inputStream = null;
		try {
			// 创建一个URL对象
			url = new URL(urlStr);
			// 根据URL对象创建一个HttpURLConnection连接
			HttpURLConnection urlConn = (HttpURLConnection) url
					.openConnection();
			// IO流读取数据
			inputStream = urlConn.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return inputStream;
	}

}

AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="android.apps"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.   
  7.   
  8.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  9.         <activity android:name=".DownLoad"  
  10.                   android:label="@string/app_name">  
  11.             <intent-filter>  
  12.                 <action android:name="android.intent.action.MAIN" />  
  13.                 <category android:name="android.intent.category.LAUNCHER" />  
  14.             </intent-filter>  
  15.         </activity>  
  16.   
  17.     </application>  
  18.     <!-- 连接到网络的权限 -->  
  19.     <uses-permission android:name="android.permission.INTERNET"/>  
  20.     <!-- 访问SDcard的权限 -->  
  21.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  22. </manifest>  
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="android.apps"
      android:versionCode="1"
      android:versionName="1.0">


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".DownLoad"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <!-- 连接到网络的权限 -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <!-- 访问SDcard的权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>


希望对大家有帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值