android开发之下载文本、音乐文件
来源:互联网 发布:vmware p2v迁移linux 编辑:程序博客网 时间:2024/05/21 08:37
今天和大家分享一下在android上怎么下载文件到手机上。
主要有两点大类容:
一,通过Http协议下载文件。
创建一个HttpURLConnection对象
- HttpURLConnection urlConn = (HttpURLConnection) url
- .openConnection();
获得一个InputStream对象
- inputStream = urlConn.getInputStream();
访问网络的权限
- <uses-permission android:name="android.permission.INTERNET"/>
二,将下载的文件写入SDcard。
得到当前设备的SD卡目录
- Environment.getExternalStorageDirectory()
设置访问SD卡的权限
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
下面给出具体的代码:
DownLoad.java
- 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
- 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
- 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
- <?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>
希望对大家有帮助。
1 0
- android开发之下载文本、音乐文件
- android开发之下载文本、音乐文件
- Android开发之下载文件
- servlet之下载文件
- jsp之下载文件
- JavaWeb之下载文件
- springmvc之下载文件
- MyCnCart之下载文件
- .NetCore之下载文件
- Android开发加载音乐文件时
- Android开发:扫描本地音乐文件
- JAX-RS之下载文件
- android示例之下载文件并写入到SD卡的指定目录中
- android示例之下载文件并写入到SD卡的指定目录中
- FTP文件操作之下载文件
- socket编程学习之下载文件
- Android 获取sdcard音乐文件
- android播放音乐文件代码
- APPIUM+JAVA实现对安卓APK的自动化测试----第十一篇【定位元素】
- 开发错误记录3 Error:failed to find Build Tools revision 23.0.2 rc2
- 3727: PA2014 Final Zadanie|树形DP
- C++ explicit的作用
- AS数倍提高工作效率的快捷键
- android开发之下载文本、音乐文件
- x264代码剖析(七):encode()函数之x264_encoder_encode()函数
- Android高效编程的一些知识
- 在O2O路上,横躺着众多一窝蜂后惨死路边的案例
- linux kernel 中断子系统 -- ARM GIC 硬件
- window7 ubuntu双系统安装
- Android保持屏幕常亮唤醒状态
- ios 常用第三方类库
- Mysql 事务