zoukankan      html  css  js  c++  java
  • Android下载文本文件和mp3文件

    布局文件main.xml

    main.xml
     1 <?xml version="1.0" encoding="utf-8"?>
    2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3 android:layout_width="fill_parent"
    4 android:layout_height="fill_parent"
    5 android:orientation="vertical" >
    6
    7 <Button
    8 android:id="@+id/downloadTxt"
    9 android:layout_width="fill_parent"
    10 android:layout_height="wrap_content"
    11 android:text="Download text"/>
    12 <Button
    13 android:id="@+id/downloadMp3"
    14 android:layout_width="fill_parent"
    15 android:layout_height="wrap_content"
    16 android:text="Download MP3"/>
    17 </LinearLayout>

    Activity文件DownloadFileToSDKCardActivity.java

    DownloadFileToSDKCardActivity.java
     1 package paul.Activity;
    2
    3 import paul.utils.HttpDownloadUtil;
    4 import android.app.Activity;
    5 import android.os.Bundle;
    6 import android.view.View;
    7 import android.view.View.OnClickListener;
    8 import android.widget.Button;
    9
    10 //创建一个HttpURLConnection对象
    11 //HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
    12 //获取一个InputStream对象
    13 //InputStream is=urlConn.getInputStream();
    14 //访问网络权限
    15 //android.permission.INTERNET
    16 //得到当前设备SD卡的目录
    17 //Environment.getExternalStorageDirectory()
    18 //访问SD卡的权限
    19 //android.permission.WEITE_EXTERNAL_STORAGE
    20 public class DownloadFileToSDKCardActivity extends Activity {
    21 /** Called when the activity is first created. */
    22 HttpDownloadUtil httpDownloadUtil;
    23 private Button downloadTxt;
    24 private Button downloadMp3;
    25 public DownloadFileToSDKCardActivity(){
    26 httpDownloadUtil=new HttpDownloadUtil();
    27 }
    28 @Override
    29 public void onCreate(Bundle savedInstanceState) {
    30 super.onCreate(savedInstanceState);
    31 setContentView(R.layout.main);
    32 downloadTxt=(Button) this.findViewById(R.id.downloadTxt);
    33 downloadTxt.setOnClickListener(new DownloadTxt());
    34 downloadMp3=(Button) this.findViewById(R.id.downloadMp3);
    35 downloadMp3.setOnClickListener(new DownloadMp3());
    36 }
    37
    38
    39 class DownloadTxt implements OnClickListener{
    40
    41 @Override
    42 public void onClick(View arg0) {
    43 String url="http://www.baidu.com";
    44 System.out.println(httpDownloadUtil.downFile(url));
    45 }
    46
    47 }
    48
    49 class DownloadMp3 implements OnClickListener{
    50
    51 @Override
    52 public void onClick(View arg0) {
    53 String url="http://media.ringring.vn/ringtone/realtone/0/0/161/165346.mp3";
    54 //int index=url.lastIndexOf("/");
    55 //String fileName=url.substring(index+1);
    56 int result=httpDownloadUtil.downFile(url, "music", "aa.mp3");
    57 System.out.println(result);
    58 }
    59
    60 }
    61 }

    文件下载类HttpDownloadUtil.java

    HttpDownloadUtil.java
     1 package paul.utils;
    2
    3 import java.io.BufferedReader;
    4 import java.io.File;
    5 import java.io.IOException;
    6 import java.io.InputStream;
    7 import java.io.InputStreamReader;
    8 import java.net.HttpURLConnection;
    9 import java.net.MalformedURLException;
    10 import java.net.URL;
    11
    12 public class HttpDownloadUtil {
    13
    14 /**
    15 * 根据URL下载文件,前提是这个文件当中的内容是文本,函数返回值是文件当中的文本内容
    16 * @param urlstr
    17 * @return
    18 */
    19 public String downFile(String urlstr){
    20 StringBuffer sb=new StringBuffer();
    21 BufferedReader buffer=null;
    22 URL url=null;
    23 String line=null;
    24 try {
    25 //创建一个URL对象
    26 url=new URL(urlstr);
    27 //根据URL对象创建一个Http连接
    28 HttpURLConnection urlConn=(HttpURLConnection) url.openConnection();
    29 //使用IO读取下载的文件数据
    30 buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    31 while((line=buffer.readLine())!=null){
    32 sb.append(line);
    33 }
    34 } catch (MalformedURLException e) {
    35 // TODO Auto-generated catch block
    36 e.printStackTrace();
    37 } catch (IOException e) {
    38 // TODO Auto-generated catch block
    39 e.printStackTrace();
    40 }finally{
    41 try {
    42 buffer.close();
    43 } catch (IOException e) {
    44 e.printStackTrace();
    45 }
    46 }
    47 return sb.toString();
    48 }
    49
    50 /**
    51 * 该函数返回整形 -1:代表下载文件错误0 :下载文件成功1:文件已经存在
    52 * @param urlstr
    53 * @param path
    54 * @param fileName
    55 * @return
    56 */
    57 public int downFile(String urlstr,String path,String fileName){
    58 InputStream inputStream=null;
    59 FileUtils fileUtils=new FileUtils();
    60
    61 if(fileUtils.isFileExist(path+fileName)){
    62 return 1;
    63 }else{
    64 inputStream=getInputStreamFormUrl(urlstr);
    65 File resultFile=fileUtils.writeToSDfromInput(path, fileName, inputStream);
    66 if(resultFile==null){
    67 return -1;
    68 }
    69 }
    70 return 0;
    71 }
    72
    73 /**
    74 * 根据URL得到输入流
    75 * @param urlstr
    76 * @return
    77 */
    78 public InputStream getInputStreamFormUrl(String urlstr){
    79 InputStream inputStream=null;
    80 try {
    81 URL url=new URL(urlstr);
    82 HttpURLConnection urlConn=(HttpURLConnection) url.openConnection();
    83 inputStream=urlConn.getInputStream();
    84 } catch (MalformedURLException e) {
    85 e.printStackTrace();
    86 } catch (IOException e) {
    87 e.printStackTrace();
    88 }
    89 return inputStream;
    90 }
    91 }

    保存文件到SD卡通用工具类FileUtils.java

    FileUtils.java
     1 package paul.utils;
    2
    3 import java.io.File;
    4 import java.io.FileNotFoundException;
    5 import java.io.FileOutputStream;
    6 import java.io.IOException;
    7 import java.io.InputStream;
    8 import java.io.OutputStream;
    9
    10 import android.os.Environment;
    11
    12 public class FileUtils {
    13 private String SDPath;
    14
    15 public FileUtils(){
    16 //得到当前外部存储设备的目录
    17 SDPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
    18 }
    19
    20 /**
    21 * 在SD卡上创建文件
    22 * @param fileName
    23 * @return
    24 */
    25 public File createSDFile(String fileName){
    26 File file=new File(SDPath+fileName);
    27 try {
    28 file.createNewFile();
    29 } catch (IOException e) {
    30 e.printStackTrace();
    31 }
    32 return file;
    33 }
    34
    35 /**
    36 * 在SD卡上创建目录
    37 * @param dirName
    38 * @return
    39 */
    40 public File createSDDir(String dirName){
    41 File file=new File(SDPath+dirName);
    42 file.mkdir();
    43 return file;
    44 }
    45
    46 /**
    47 * 判断SD卡上文件是否存在
    48 * @param fileName
    49 * @return
    50 */
    51 public boolean isFileExist(String fileName){
    52 File file=new File(SDPath+fileName);
    53 return file.exists();
    54 }
    55 /**
    56 * 将一个inputStream里面的数据写到SD卡中
    57 * @param path
    58 * @param fileName
    59 * @param inputStream
    60 * @return
    61 */
    62 public File writeToSDfromInput(String path,String fileName,InputStream inputStream){
    63 //createSDDir(path);
    64 File file=createSDFile(path+fileName);
    65 OutputStream outStream=null;
    66 try {
    67 outStream=new FileOutputStream(file);
    68 byte[] buffer=new byte[4*1024];
    69 while(inputStream.read(buffer)!=-1){
    70 outStream.write(buffer);
    71 }
    72 outStream.flush();
    73 } catch (FileNotFoundException e) {
    74 e.printStackTrace();
    75 } catch (IOException e) {
    76 e.printStackTrace();
    77 }finally{
    78 try {
    79 outStream.close();
    80 } catch (IOException e) {
    81 e.printStackTrace();
    82 }
    83 }
    84 return file;
    85 }
    86 }

    AndroidManifest.xml

    AndroidManifest.xml
     1 <?xml version="1.0" encoding="utf-8"?>
    2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    3 package="paul.Activity"
    4 android:versionCode="1"
    5 android:versionName="1.0" >
    6
    7 <uses-sdk android:minSdkVersion="10" />
    8 <uses-permission android:name="android.permission.INTERNET" />
    9 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    10 <application
    11 android:icon="@drawable/ic_launcher"
    12 android:label="@string/app_name" >
    13 <activity
    14 android:name=".DownloadFileToSDKCardActivity"
    15 android:label="@string/app_name" >
    16 <intent-filter>
    17 <action android:name="android.intent.action.MAIN" />
    18
    19 <category android:name="android.intent.category.LAUNCHER" />
    20 </intent-filter>
    21 </activity>
    22 </application>
    23 </manifest>
  • 相关阅读:
    变量定义和声明的差别(整理)
    堆栈指针理解
    HDU 4349 Xiao Ming&#39;s Hope
    iOS 8中CLLocationManager及MKMapView showUserLocation失败的解决的方法
    Ant命令行操作
    linux awk命令详细使用方法
    mysql 修改[取消]timestamp的自动更新
    cocos2d-x 3.0游戏实例学习笔记《卡牌塔防》第六步---炮台&amp;点击炮台加入英雄&amp;英雄升级
    SendMessage、PostMessage原理
    poj 2104 K-th Number 主席树+超级详细解释
  • 原文地址:https://www.cnblogs.com/Laupaul/p/2348293.html
Copyright © 2011-2022 走看看