Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类

2024-05-24 03:18

本文主要是介绍Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


(1)文件的目录


(2)各文件的代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".MainActivity" ><ImageViewandroid:id="@+id/imageView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_alignRight="@+id/button1"android:layout_marginRight="44dp"android:layout_marginTop="78dp"android:src="@drawable/ic_launcher" /><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_below="@+id/imageView1"android:layout_marginLeft="96dp"android:layout_marginTop="106dp"android:text="Button" /></RelativeLayout>


FileService.java也就是操作sdcard的工具类:

package com.example.data_storage_sdcard.file;import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;import android.os.Environment;/*** sdcard的存在于上下文无关* * @author piaodangdehun* */
public class FileService {/** 存放在sdcard的根目录*/public boolean saveFileToSdcardRoot(String fileName, byte[] data) {boolean flag = false;/** 先判断sdcard的状态,是否存在*/String state = Environment.getExternalStorageState();FileOutputStream outputStream = null;File rootFile = Environment.getExternalStorageDirectory(); // 获得sdcard的根路径/** 表示sdcard挂载在手机上,并且可以读写*/if (state.equals(Environment.MEDIA_MOUNTED)) {File file = new File(rootFile, fileName);try {outputStream = new FileOutputStream(file);try {outputStream.write(data, 0, data.length);flag = true;} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e) {e.printStackTrace();} finally {if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}return flag;}/** 存放在sdcard下自定义的目录*/public boolean saveFileToSdcardDir(String fileName, byte[] data) {boolean flag = false;/** 先判断sdcard的状态,是否存在*/String state = Environment.getExternalStorageState();FileOutputStream outputStream = null;File rootFile = Environment.getExternalStorageDirectory(); // 获得sdcard的根路径/** 表示sdcard挂载在手机上,并且可以读写*/if (state.equals(Environment.MEDIA_MOUNTED)) {File file = new File(rootFile.getAbsoluteFile() + "/txt");if (!file.exists()) {file.mkdirs();}try {outputStream = new FileOutputStream(new File(file, fileName));try {outputStream.write(data, 0, data.length);flag = true;} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e) {e.printStackTrace();} finally {if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}return flag;}/** 用于读取sdcard的数据*/public String readContextFromSdcard(String fileName) {String state = Environment.getExternalStorageState();File rooFile = Environment.getExternalStorageDirectory(); // 获得sdcard的目录FileInputStream inputStream = null;// 用于度取数据的流ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 用于存放独处的数据if (state.equals(Environment.MEDIA_MOUNTED)) {File file = new File(rooFile.getAbsoluteFile() + "/txt/");// 在sdcard目录下创建一个txt目录File file2 = new File(file, fileName);int len = 0;byte[] data = new byte[1024];if (file2.exists()) {try {inputStream = new FileInputStream(file2);try {while ((len = inputStream.read(data)) != -1) {outputStream.write(data, 0, data.length);}} catch (IOException e) {e.printStackTrace();}return new String(outputStream.toByteArray());} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}}return null;}/*** 对文件进行分类的保存到固定的文件中去* * @param fileName* @param data*/public void saveFileToSdcardBySuff(String fileName, byte[] data) {// File file = Environment.getExternalStoragePublicDirectory("");// 保存文件的目录File file = null;if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {/** 将不同的文件放入到不同的类别中*/if (fileName.endsWith(".mp3")) {file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);} else if (fileName.endsWith(".jpg") || fileName.endsWith(".png")|| fileName.endsWith(".gif")) {file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);} else if (fileName.endsWith(".mp4") || fileName.endsWith(".avi")|| fileName.endsWith(".3gp")) {file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);} else {file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);}FileOutputStream outputStream = null;try {outputStream = new FileOutputStream(new File(file, fileName));try {outputStream.write(data, 0, data.length);} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e) {e.printStackTrace();} finally {if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}}/** 删除一个文件*/public boolean deleteFileFromSdcard(String folder, String fileName) {boolean flag = false;File file = Environment.getExternalStorageDirectory();if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {File exitFile = new File(file.getAbsoluteFile() + "/" + folder);if (exitFile.exists()) {exitFile.delete();}}return flag;}
}

HttpUtils.java访问网络的

package com.example.data_storage_sdcard.http;import java.io.IOException;import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;public class HttpUtils {/** */public static byte[] getImage(String path) {byte[] data = null;HttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(path);try {HttpResponse response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() == 200) {data = EntityUtils.toByteArray(response.getEntity());}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {httpClient.getConnectionManager().shutdown();}return data;}
}

ImageCache.java将文件放到cache中的:

package com.example.data_storage_sdcard.img;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;import android.os.Environment;public class ImageCache {public static  String saveImageCache(String fileName, byte[] data) {File file = Environment.getExternalStorageDirectory(); // 根目录FileOutputStream outputStream = null;if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {try {outputStream = new FileOutputStream(new File(file, fileName));outputStream.write(data, 0, data.length);return file.getAbsolutePath() + "/" + fileName;} catch (Exception e) {e.printStackTrace();} finally {if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}return null;}
}

MainActivity.java

package com.example.data_storage_sdcard;import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;import com.example.data_storage_sdcard.http.HttpUtils;
import com.example.data_storage_sdcard.img.ImageCache;public class MainActivity extends Activity {private Button button;private ImageView imageView;private ProgressDialog progressDialog;private String imageName;private final String pathString = "http://www.baidu.com/img/bd_logo1.png";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button) this.findViewById(R.id.button1);imageView = (ImageView) this.findViewById(R.id.imageView1);progressDialog = new ProgressDialog(this);progressDialog.setTitle("下载提示");progressDialog.setMessage("load...");button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {new MyTask().execute(pathString);}});}class MyTask extends AsyncTask<String, Void, byte[]> {@Overrideprotected void onPreExecute() {super.onPreExecute();progressDialog.show();}@Overrideprotected byte[] doInBackground(String... params) {String name = params[0];imageName = name.substring(name.lastIndexOf("/") + 1, name.length());return HttpUtils.getImage(params[0]);}@Overrideprotected void onProgressUpdate(Void... values) {super.onProgressUpdate(values);}@Overrideprotected void onPostExecute(byte[] result) {super.onPostExecute(result);if (result != null) {Bitmap bm = BitmapFactory.decodeByteArray(result, 0,result.length);imageView.setImageBitmap(bm);ImageCache.saveImageCache("", result);} else {imageView.setImageResource(R.drawable.ic_launcher);}progressDialog.dismiss();}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

测试类:

package com.example.data_storage_sdcard;import java.io.FileWriter;import com.example.data_storage_sdcard.file.FileService;import android.nfc.Tag;
import android.test.AndroidTestCase;
import android.util.Log;public class MyTest extends AndroidTestCase {public void saveFileToSdcardTest() {FileService fileService = new FileService();fileService.saveFileToSdcardRoot("aa.txt","jkhdsfjkhdskjfhdsjf".getBytes());}public void saveFileToSdcardDir() {FileService fileService = new FileService();fileService.saveFileToSdcardRoot("aa.txt","jkhdsfjkhdskjfhdsjf".getBytes());}public void readContextFromSdcardTest() {FileService fileService = new FileService();String msg = fileService.readContextFromSdcard("aa.txt");System.err.println("-->" + msg);}public void saveFileToSdcardBySuffTest() {FileService fileService = new FileService();fileService.saveFileToSdcardBySuff("aa.avi","asdfkajsgdhagsdfhdgsf".getBytes());}public void delFile() {FileService fileService = new FileService();boolean flag = fileService.deleteFileFromSdcard("txt", "aa.txt");}
}

需要在请单位按中加入访问网络的权限、操作sdcard的权限、测试的权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.data_storage_sdcard"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="18" /><instrumentationandroid:name="android.test.InstrumentationTestRunner"android:targetPackage="com.example.data_storage_sdcard" ></instrumentation><!-- 添加访问sdcard的权限 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><!-- 添加访问网络的权限 --><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><uses-library android:name="android.test.runner" /><activityandroid:name="com.example.data_storage_sdcard.MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><uses-library></uses-library></application></manifest>




这篇关于Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/997217

相关文章

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain

Android中Dialog的使用详解

《Android中Dialog的使用详解》Dialog(对话框)是Android中常用的UI组件,用于临时显示重要信息或获取用户输入,本文给大家介绍Android中Dialog的使用,感兴趣的朋友一起... 目录android中Dialog的使用详解1. 基本Dialog类型1.1 AlertDialog(

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优

Mysql表的简单操作(基本技能)

《Mysql表的简单操作(基本技能)》在数据库中,表的操作主要包括表的创建、查看、修改、删除等,了解如何操作这些表是数据库管理和开发的基本技能,本文给大家介绍Mysql表的简单操作,感兴趣的朋友一起看... 目录3.1 创建表 3.2 查看表结构3.3 修改表3.4 实践案例:修改表在数据库中,表的操作主要

C# WinForms存储过程操作数据库的实例讲解

《C#WinForms存储过程操作数据库的实例讲解》:本文主要介绍C#WinForms存储过程操作数据库的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、存储过程基础二、C# 调用流程1. 数据库连接配置2. 执行存储过程(增删改)3. 查询数据三、事务处

macOS无效Launchpad图标轻松删除的4 种实用方法

《macOS无效Launchpad图标轻松删除的4种实用方法》mac中不在appstore上下载的应用经常在删除后它的图标还残留在launchpad中,并且长按图标也不会出现删除符号,下面解决这个问... 在 MACOS 上,Launchpad(也就是「启动台」)是一个便捷的 App 启动工具。但有时候,应

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

Java利用JSONPath操作JSON数据的技术指南

《Java利用JSONPath操作JSON数据的技术指南》JSONPath是一种强大的工具,用于查询和操作JSON数据,类似于SQL的语法,它为处理复杂的JSON数据结构提供了简单且高效... 目录1、简述2、什么是 jsONPath?3、Java 示例3.1 基本查询3.2 过滤查询3.3 递归搜索3.4

SpringBoot日志配置SLF4J和Logback的方法实现

《SpringBoot日志配置SLF4J和Logback的方法实现》日志记录是不可或缺的一部分,本文主要介绍了SpringBoot日志配置SLF4J和Logback的方法实现,文中通过示例代码介绍的非... 目录一、前言二、案例一:初识日志三、案例二:使用Lombok输出日志四、案例三:配置Logback一