`
shenjichao2009
  • 浏览: 94433 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Android中下载文件的使用

阅读更多

DownloadActivity.java

package com.duoguo.android;

import com.duoguo.util.DownloadUtil;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * 文件下载
 *
 * @author shyboy(
897948924@qq.com)
 *
 */

public class DownloadActivity extends Activity {

 // 声明Button控件
 private Button downloadTextFileButton;
 private Button downloadMP3FileButton;

 @Override
 public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  // 获取Button控件
  downloadTextFileButton = (Button) findViewById(R.id.downLoadTextFileId);
  downloadMP3FileButton = (Button) findViewById(R.id.downLoadMP3FileId);

  // 为Button控件添加事件单击监听器
  downloadTextFileButton
    .setOnClickListener(new DownloadTextFileClickListener());
  downloadMP3FileButton
    .setOnClickListener(new DownloadMP3FileClickListener());

 }

 // 为downloadTextFileButton控件编写监听器
 class DownloadTextFileClickListener implements OnClickListener {

  @Override
  public void onClick(View v) {

   String textContent = DownloadUtil
     .download("
http://dldx.csdn.net/fd.php?i=232723316503113&s=62d4f87fc08bc83113919d484d8a5dbb");// 下载文本内容
   System.out.println("歌词内容为:" + textContent);

  }

 }

 // 为downloadMP3FileButton控件编写监听器
 class DownloadMP3FileClickListener implements OnClickListener {

  @Override
  public void onClick(View v) {

   String mp3Content = DownloadUtil
     .download(
       "
http://dldx.csdn.net/fd.php?i=232723316503113&s=62d4f87fc08bc83113919d484d8a5dbb",
       "/MP3/", "view.ppt", false);
   System.out.println("MP3:" + mp3Content);

  }

 }

}

 

DownloadUtil.java

/**
 *
 */
package com.duoguo.util;

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;

import android.util.Log;

/**
 * 文件下载帮助类
 *
 * @author shyboy(
897948924@qq.com)
 *
 */
public class DownloadUtil {

 private static URL url;// 下载文件的地址

 /**
  * 下载文本文件
  *
  * @param urlStr
  *            :文件的下载链接地址
  * @return String:文本文件的内容
  */
 public static String download(String urlStr) {

  StringBuilder sb = new StringBuilder();
  String line = null;
  BufferedReader bufferedReader = null;

  try {

   url = new URL(urlStr);// 创建URL对象
   HttpURLConnection httpURLConnection = (HttpURLConnection) url
     .openConnection();// 获取HttpURLConnection连接对象

   bufferedReader = new BufferedReader(new InputStreamReader(
     httpURLConnection.getInputStream()));// 获取BufferedReader对象
   while ((line = bufferedReader.readLine()) != null) {
    sb.append(line);
   }

  } catch (MalformedURLException e) {

   e.printStackTrace();
   Log.d("debug", e.getMessage());

  } catch (IOException e) {

   e.printStackTrace();
   Log.d("debug", e.getMessage());

  } finally {
   try {

    bufferedReader.close();// 关闭流

   } catch (IOException e) {

    e.printStackTrace();
    Log.d("debug", e.getMessage());

   }
  }

  return sb.toString();

 }

 /**
  * 下载MP3文件
  *
  * @param urlStr
  *            :文件的下载链接地址
  * @param path
  *            :下载文件的存放路径
  * @param fileName
  *            :下载文件的名称
  * @param isReplace
  *            :是否替换已存在的文件
  * @return String:FAILURE/SUCCESS/EXIST
  */
 public static String download(String urlStr, String path, String fileName,
   boolean isReplace) {

  InputStream inputStream = null;
  File downloadFile = null;

  if (FileUtil.isFileExist(path + fileName))// 当文件存在时
  {

   if (isReplace)// 当替换文件时
   {
    inputStream = getInputStreamFromUrl(urlStr);// 根据URL获取相应的InputStream输入流对象
    downloadFile = FileUtil.writeToSDCardFromInput(path, fileName,
      inputStream);// 通过输入流向SDCard中写入文件

    if (null == downloadFile) {

     return DownloadEnum.FAILURE.toString();// 下载失败

    } else {

     return DownloadEnum.SUCCESS.toString();// 下载成功

    }
   } else {

    return DownloadEnum.EXIST.toString();// 文件已存在

   }

  } else {

   inputStream = getInputStreamFromUrl(urlStr);// 根据URL获取相应的InputStream输入流对象
   downloadFile = FileUtil.writeToSDCardFromInput(path, fileName,
     inputStream);// 通过输入流向SDCard中写入文件

   if (null == downloadFile) {

    return DownloadEnum.FAILURE.toString();// 下载失败

   } else {

    return DownloadEnum.SUCCESS.toString();// 下载成功

   }

  }

 }

 /**
  * 根据URL获取相应的InputStream输入流对象
  *
  * @param urlStr
  *            :文件的链接地址
  * @return InputStream
  */
 public static InputStream getInputStreamFromUrl(String urlStr) {

  InputStream inputStream = null;

  try {

   URL url = new URL(urlStr);
   HttpURLConnection httpURLConnection = (HttpURLConnection) url
     .openConnection();
   inputStream = httpURLConnection.getInputStream();

  } catch (MalformedURLException e) {

   e.printStackTrace();
   Log.e("debug", e.getMessage());

  } catch (IOException e) {

   e.printStackTrace();
   Log.e("debug", e.getMessage());

  }

  return inputStream;

 }

}

FileUtil.java

/**
 *
 */
package com.duoguo.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;
import android.util.Log;

/**
 * 文件操作类
 *
 * @author shyboy(
897948924@qq.com)
 *
 */
public class FileUtil {

 private static String SDPATH = Environment.getExternalStorageDirectory()
   + "/";// SDCard的目录名称

 public FileUtil() {

  SDPATH = Environment.getExternalStorageDirectory() + "/";// 获取当前外部存储设备的目录
  System.out.println("SDCard:" + SDPATH);

 }

 /**
  * 创建SDCard文件
  *
  * @param fileName
  *            :文件名称
  * @return File:文件对象
  */
 public static File createSDCardFile(String fileName) {

  File file = null;

  if ((null != SDPATH && !"".equals(SDPATH))
    && (null != fileName && !"".equals(fileName))) {

   file = new File(SDPATH + fileName);// 生成文件对象
   if (null != file && !file.exists()) {
    try {

     file.createNewFile();// 创建新文件

    } catch (IOException e) {

     e.printStackTrace();
     Log.d("debug", e.getMessage());

    }
   }

  }

  return file;

 }

 /**
  * 创建SDCard目录
  *
  * @param dirName
  *            :文件目录
  * @return File:文件对象
  */
 public static File createSDCardDir(String dirName) {

  File dir = null;

  dir = new File(SDPATH + dirName);// 生成文件目录对象
  if (null != dir && !dir.exists()) {
   dir.mkdirs();// 创建文件目录
  }

  return dir;

 }

 /**
  * 判断文件是否存在
  *
  * @param fileName
  *            :文件名称
  * @return boolean:true/false
  */
 public static boolean isFileExist(String fileName) {

  if ((null != SDPATH && !"".equals(SDPATH))
    && (null != fileName && !"".equals(fileName))) {

   File file = new File(SDPATH + fileName);

   if (null != file) {
    if (file.exists()) {
     return true;
    } else {
     return false;
    }
   }

  }

  return false;

 }

 /**
  * 通过输入流向SDCard中写入文件
  *
  * @param path
  *            :文件存放在SDCard上的路径
  * @param fileName
  *            :文件名称
  * @param inputStream
  *            :输入流对象
  * @return File:文件对象
  */
 public static File writeToSDCardFromInput(String path, String fileName,
   InputStream inputStream) {

  File file = null;
  OutputStream outputStream = null;

  if (null != path && !"".equals(path)) {

   createSDCardDir(path);// 创建文件目录

   if (null != fileName && !"".equals(fileName)) {

    file = createSDCardFile(path + fileName);// 创建文件
    if (null != file) {

     try {

      outputStream = new FileOutputStream(file);// 创建OutputStream输出流对象
      byte[] buffer = new byte[4 * 1024];

      while ((inputStream.read(buffer)) != -1)// 将写入的内容写到字节数组中
      {
       try {

        outputStream.write(buffer);// 将字节数组中读取的内容写入到输出流中

       } catch (IOException e) {
        e.printStackTrace();
       }
      }

      outputStream.flush();// 清理输出流通道

     } catch (FileNotFoundException e) {

      e.printStackTrace();
      Log.e("debug", e.getMessage());

     } catch (IOException e) {

      e.printStackTrace();
      Log.e("debug", e.getMessage());

     } finally {

      try {

       inputStream.close();// 关闭输入流(用来读取数据)
       outputStream.close();// 关闭输出流(用来写入数据)

      } catch (IOException e) {

       e.printStackTrace();
       Log.e("debug", e.getMessage());

      }

     }

    }

   }

  }

  return file;

 }

 /**
  * 获取SDCard的目录名称
  *
  * @return String
  */
 public String getSDPATH() {
  return SDPATH;
 }

 /**
  * 设置SDCard的目录名称
  *
  * @param sDPATH
  *            :SDCard的路径
  */
 public void setSDPATH(String sDPATH) {
  SDPATH = sDPATH;
 }

}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <Button android:id="@+id/downLoadTextFileId"
  android:layout_width="fill_parent" android:layout_height="wrap_content"
  android:text="@string/downLoadTextFile" android:layout_margin="10px"
  android:layout_gravity="center" android:gravity="center" />

 <Button android:id="@+id/downLoadMP3FileId"
  android:layout_width="fill_parent" android:layout_height="wrap_content"
  android:text="@string/downLoadMP3File" android:layout_margin="10px"
  android:layout_gravity="center" android:gravity="center" />

</LinearLayout>

 

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <string name="app_name">Download</string>
 <string name="downLoadTextFile">下载文本文件</string>
 <string name="downLoadMP3File">下载MP3文件</string>
</resources>

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="
http://schemas.android.com/apk/res/android"
 package="com.duoguo.android" android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="8" />

 <application android:icon="@drawable/icon" android:label="@string/app_name">
  <activity android:name=".DownloadActivity" 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" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

</manifest>

分享到:
评论
2 楼 shenjichao2009 2011-11-30  
anyang763 写道
谢啦,刚好用到

客气了
1 楼 anyang763 2011-11-30  
谢啦,刚好用到

相关推荐

Global site tag (gtag.js) - Google Analytics