zoukankan      html  css  js  c++  java
  • Android学习笔记12——内存卡操作及文件下载功能的实现

    一、权限的获取:

    应用程序如要要使用联网功能,或者是操作SD卡,需要在AndroidManifest.xml中配置相应的权限:

    [xhtml] view plaincopy
     
    1. <!-- 联网权限 -->  
    2. <uses-permission android:name="android.permission.INTERNET"/>  
    3. <!-- SD卡操作权限 -->  
    4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

    二、要操作SD卡,首先要读取它在Android操作系统中的路径:

    [java] view plaincopy
     
    1. SDCardPath = Environment.getExternalStorageDirectory() + "/";  

    三、获取了SD卡的路径之后的操作,同于Java中的文件IO操作,此不赘述。

    四、网络操作

    1、由URL获取HTTP连接

    [java] view plaincopy
     
    1. import java.net.HttpURLConnection;  
    2. import java.net.URL;  
    3. url = new URL(strUrl); // 获取URL  
    4. // 获取HTTP连接  
    5. urlConn = (HttpURLConnection) url.openConnection();  

    2、由HTTP连接获取输入字节流

    [java] view plaincopy
     
    1. java.io.InputStream = urlConn.getInputStream()  

    3、其它操作同Java IO操作

    五、示例代码:下载一个文本文件在控制行输出其内容,再下载这个文件保存早SD卡下

    1、AndroidManifest.xml

    [xhtml] view plaincopy
     
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    3.       package="me.bym"  
    4.       android:versionCode="1"  
    5.       android:versionName="1.0">  
    6.     <uses-sdk android:minSdkVersion="4" />  
    7.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
    8.         <activity android:name=".DownLoadActivity"  
    9.                   android:label="@string/app_name">  
    10.             <intent-filter>  
    11.                 <action android:name="android.intent.action.MAIN" />  
    12.                 <category android:name="android.intent.category.LAUNCHER" />  
    13.             </intent-filter>  
    14.         </activity>  
    15.     </application>  
    16.     <uses-permission android:name="android.permission.INTERNET"/>  
    17.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
    18. </manifest>  

    2、文件操作类FileHelper.java

    [java] view plaincopy
     
    1. package me.bym.utils;  
    2. import java.io.File;  
    3. import java.io.FileOutputStream;  
    4. import java.io.IOException;  
    5. import java.io.InputStream;  
    6. import java.io.OutputStream;  
    7. import android.os.Environment;  
    8. public class FileHelper {  
    9.     private String SDCardPath = null; // SD卡在Android文件系统中的路径  
    10.     public String getPath() {  
    11.         return SDCardPath;  
    12.     }  
    13.     /** 
    14.      * 构造方法,获取SD卡在Android文件系统中的路径 
    15.      */  
    16.     public FileHelper() {  
    17.         SDCardPath = Environment.getExternalStorageDirectory() + "/";  
    18.     }  
    19.     /** 
    20.      * 在SD卡上创建文件 
    21.      *  
    22.      * @param fileName 
    23.      *            要创建的文件名 
    24.      * @return 创建得到的文件 
    25.      */  
    26.     public File createSDFile(String fileName) throws IOException {  
    27.         File file = new File(SDCardPath + fileName);  
    28.         file.createNewFile();  
    29.         return file;  
    30.     }  
    31.     /** 
    32.      * 在SD卡上创建目录 
    33.      *  
    34.      * @param dirName 
    35.      *            要创建的目录名 
    36.      * @return 创建得到的目录 
    37.      */  
    38.     public File createSDDir(String dirName) {  
    39.         File dir = new File(SDCardPath + dirName);  
    40.         dir.mkdir();  
    41.         return dir;  
    42.     }  
    43.     /** 
    44.      * 判断文件是否已经存在 
    45.      *  
    46.      * @param fileName 
    47.      *            要检查的文件名 
    48.      * @return boolean, true表示存在,false表示不存在 
    49.      */  
    50.     public boolean isFileExist(String fileName) {  
    51.         File file = new File(SDCardPath + fileName);  
    52.         return file.exists();  
    53.     }  
    54.     /** 
    55.      * 将一个输入流中的内容写入到SD卡上生成文件 
    56.      *  
    57.      * @param path 
    58.      *            文件目录 
    59.      * @param fileName 
    60.      *            文件名 
    61.      * @param inputStream 
    62.      *            字节输入流 
    63.      * @return 得到的文件 
    64.      */  
    65.     public File writeToSDCard(String path, String fileName,  
    66.             InputStream inputStream) {  
    67.         File file = null;  
    68.         OutputStream output = null;  
    69.         try{  
    70.             createSDDir(path);  
    71.             file = createSDFile(path + fileName);  
    72.             output = new FileOutputStream(file);  
    73.             byte buffer [] = new byte[4 * 1024];  
    74.             while((inputStream.read(buffer)) != -1){  
    75.                 output.write(buffer);  
    76.             }  
    77.             output.flush();  
    78.         }  
    79.         catch(Exception e){  
    80.             e.printStackTrace();  
    81.         }  
    82.         finally{  
    83.             try{  
    84.                 output.close();  
    85.             }  
    86.             catch(Exception e){  
    87.                 e.printStackTrace();  
    88.             }  
    89.         }  
    90.         return file;  
    91.     }  
    92. }  

    3、HTTP下载操作类HttpDownloadHelper.java

    [java] view plaincopy
     
    1. package me.bym.utils;  
    2. import java.io.BufferedReader;  
    3. import java.io.File;  
    4. import java.io.IOException;  
    5. import java.io.InputStream;  
    6. import java.io.InputStreamReader;  
    7. import java.net.HttpURLConnection;  
    8. import java.net.URL;  
    9. public class HttpDownloadHelper {  
    10.     private URL url = null;  
    11.     private HttpURLConnection urlConn = null;  
    12.     private final int SUCCESS = 1;  
    13.     private final int EXIST = 0;  
    14.     private final int ERROR = -1;  
    15.     /** 
    16.      * 通过传递一个url下载对应的文本文件。 
    17.      *  
    18.      * @param strUrl 
    19.      *            下载文件的URL地址 
    20.      * @return 下载得到的文本文件内容字符串 
    21.      */  
    22.     public String textDownload(String strUrl) {  
    23.         StringBuilder sb = new StringBuilder(512); // 初始化文本内容缓冲区。  
    24.         String line = null;  
    25.         BufferedReader br = null;  
    26.         try {  
    27.             url = new URL(strUrl); // 获取URL  
    28.             // 获取HTTP连接  
    29.             urlConn = (HttpURLConnection) url.openConnection();  
    30.             br = new BufferedReader(new InputStreamReader(  
    31.                     urlConn.getInputStream()));  
    32.             while ((line = br.readLine()) != null) {  
    33.                 sb.append(line);  
    34.             }  
    35.         } catch (Exception e) {  
    36.             e.printStackTrace();  
    37.         } finally {  
    38.             try {  
    39.                 br.close();  
    40.             } catch (IOException e) {  
    41.                 e.printStackTrace();  
    42.             }  
    43.         }  
    44.         return sb.toString();  
    45.     }  
    46.     /** 
    47.      * 通过传递一个url下载对应的文件。 
    48.      *  
    49.      * @param strUrl 
    50.      *            下载文件的url地址 
    51.      * @param path 
    52.      *            保存文件的路径 
    53.      * @param fileName 
    54.      *            保存文件的文件名 
    55.      * @return SUCCESS:文件下载成功 ERROR:文件下载失败 EXIST:同名文件已存在 
    56.      */  
    57.     public int fileDownload(String strUrl, String path, String fileName) {  
    58.         FileHelper fileHelper = new FileHelper();  
    59.         InputStream inputStream = null;  
    60.         File file = null;  
    61.         if (fileHelper.isFileExist(path + fileName)) {  
    62.             return EXIST;  
    63.         } else {  
    64.             try {  
    65.                 inputStream = getInputStream(strUrl);  
    66.                 file = fileHelper.writeToSDCard(path, fileName, inputStream);  
    67.                 if (file == null) {  
    68.                     return ERROR;  
    69.                 }  
    70.             } catch (IOException e) {  
    71.                 e.printStackTrace();  
    72.             } finally {  
    73.                 try {  
    74.                     inputStream.close();  
    75.                 } catch (IOException e) {  
    76.                     e.printStackTrace();  
    77.                 }  
    78.             }  
    79.         }  
    80.         return SUCCESS;  
    81.     }  
    82.     /** 
    83.      * 通过一个url获取http连接的输入流 
    84.      *  
    85.      * @param strUrl 
    86.      *            目标url 
    87.      * @return 到该url的http连接的输入流 
    88.      * @throws IOException 
    89.      */  
    90.     private InputStream getInputStream(String strUrl) throws IOException {  
    91.         url = new URL(strUrl);  
    92.         urlConn = (HttpURLConnection) url.openConnection();  
    93.         InputStream is = urlConn.getInputStream();  
    94.         return is;  
    95.     }  
    96. }  

    4、Activity类

    [java] view plaincopy
     
    1. package me.bym;  
    2. import me.bym.utils.HttpDownloadHelper;  
    3. import android.app.Activity;  
    4. import android.os.Bundle;  
    5. import android.view.View;  
    6. import android.view.View.OnClickListener;  
    7. import android.widget.Button;  
    8. public class DownLoadActivity extends Activity {  
    9.     private Button downloadText = null;  
    10.     private Button downloadFile = null;  
    11.     /** Called when the activity is first created. */  
    12.     @Override  
    13.     public void onCreate(Bundle savedInstanceState) {  
    14.         super.onCreate(savedInstanceState);  
    15.         setContentView(R.layout.main);  
    16.         downloadText = (Button) findViewById(R.id.downloadText);  
    17.         downloadText.setOnClickListener(new downTextListener());  
    18.         downloadFile = (Button) findViewById(R.id.downloadFile);  
    19.         downloadFile.setOnClickListener(new downFileListener());  
    20.     }  
    21.     class downTextListener implements OnClickListener {  
    22.         @Override  
    23.         public void onClick(View v) {  
    24.             HttpDownloadHelper downHelper = new HttpDownloadHelper();  
    25.             String str = downHelper  
    26.                     .textDownload("http://news.swjtu.edu.cn/shownews-2638.html");  
    27.             System.out.println(str);  
    28.         }  
    29.     }  
    30.     class downFileListener implements OnClickListener {  
    31.         @Override  
    32.         public void onClick(View v) {  
    33.             HttpDownloadHelper downHelper = new HttpDownloadHelper();  
    34.             int res = downHelper.fileDownload(  
    35.                     "http://www.swjtu.edu.cn/images/swjtu_title.jpg", "myImg/", "a.html");  
    36.             switch (res) {  
    37.             case 0:  
    38.                 System.out.println("文件已存在");  
    39.                 break;  
    40.             case 1:  
    41.                 System.out.println("文件下载成功");  
    42.                 break;  
    43.             case -1:  
    44.                 System.out.println("文件下载失败");  
    45.                 break;  
    46.             }  
    47.         }  
    48.     }  
    49. }  

     http://blog.csdn.net/baoyiming1991/article/details/6307373

  • 相关阅读:
    根据表1更新表2的数据
    sql server 2008 不允许保存更改,您所做的更改要求删除并重新创建以下表
    sql server 2008 将某表里的数据随机插入另一个表表
    用SqlBulkCopy批量插入数据
    Win7 下如何添加任务计划呢
    20180320作业1:源代码管理工具调查 Polonium
    判断传入的电子邮箱账号的正确性 Polonium
    Java工厂方法模式 Polonium
    软工课后作业01 Polonium
    Java实现简单工厂模式
  • 原文地址:https://www.cnblogs.com/cmblogs/p/4386293.html
Copyright © 2011-2022 走看看