封装一个帮助类来写文件到android外置存储器上
项目地址:点击打开
项目简介:写文件到android外置存储器的一个帮助类,和它的demo程序
它是如何工作的呢?
1.创建 AppExternalFileWriter 对象并传递context(上下文);
2.按照你的要求使用 writeDataToFile 或者 writeDataToTimeStampedFile 不同的方法;
3.如果你想写入的文件需要有时间标注的数据,那么使用writeDataToTimeStampedFile类型
4.如果你想创建一个下级目录,那么可以使用灵活的 createSubDirectory类型
5.如果外置存储设比有任何的问题,比如设备没有挂载,作为大容量存储设备,空间容量不足,或者甚至是创建一个已经存在的库文件,该类运行的时候会抛出一个ExternalFileWriterException异常信息。
6.如果你想在外部缓存中写入数据,那么做如下操作:
*检查所有方法的变体(variants),它需要一个boolean类型的参数,如果你传进一个true值,文件操作在cpu缓存中已经完成了,否则将在标准外部存储器中完成。
*如果你在cpu缓存中已经通过createDirectory方法创建了一个目录,把这个目录传递给任何父类需要的方法。这些方法不管父类是在外置存储器或者cpu缓存中工作是一样的。
7.检查某些目录或者文件是否存在某些位置或者不借助isFileExists、isDirectoryExists方法。
8.用deleteDirectory方法删除整个目录。(注意:该方法之关心删除整个目录与它相关的上级目录,如果您想要检查目录是否为空并使用一些错误的消息,我推荐使用 File.delete() 方法。)
关于Variants的描述
1.writeDataToFile--没有父级目录
- writeDataToFile(String fileName, byte[] data,boolean inCache);
- writeDataToFile(String fileName, String data,boolean inCache);
在程序的目录将数据写入自定义的文件
a.writeDataToFile---在父级路径
- writeDataToFile(File parent, String fileName, byte[] data);
- writeDataToFile(File parent, String fileName, String data);
b.在其他的路径写入数据到自定义文件名称
b1 writeDataToTimeStampedFile方法---没有父级路径
- writeDataToTimeStampedFile(String extension, byte[] data,boolean inCache)
- writeDataToTimeStampedFile(String extension, String data,boolean inCache)
b2 writeDataToTimeStampedFile方法----带有父级路径
- writeDataToTimeStampedFile(String extension, byte[] data)
- writeDataToTimeStampedFile(String extension, String data)
在其他目录下写入数据到指定文件,并伴有时间标识扩展
c1 createSubDirectory方法
- createSubDirectory(File parent, String directoryName)
在其他目录下创建上级目录
- createSubDirectory(String directoryName,boolean inCache)
在应用程序目录创建上级目录
isDirectoryExists方法
- isDirectoryExists(String directoryName, boolean checkInCache)
检查赋予的目录名称是否存在在程序目录下或者缓存目录
- isDirectoryExists(String directoryName, File parentDirectory)
检查给予名称的目录是否存在与父路径
a isFileExists 方法
- isFileExists(String fileName, boolean checkInCache)
检查给予的文件名称是否存在在程序目录下(parentDirectory )
- isFileExists(String fileName, File parentDirectory)
删除目录
- deleteDirectory(File directory)
删除指定指定的目录和它上级的所有文件(翻译的还是很别扭)
一些好的建议(some goodies)
- 1.getAppDirectory() : 创建app目录的文件对象
- 2.getExternalStorageDirectory() : 获取外置存储目录文件对象
- 3.getExternalCacheDirectory() : 获取外置缓存目录对象
完整类的AppExternalFileWriter.java
- package com.example.filewrite;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import android.content.Context;
- import android.os.Environment;
- import android.os.StatFs;
- import android.text.TextUtils;
- /**
- * @author Prasham Trivedi
- * @version 2.5
- * <p>
- * This class will create a directory having same name as your
- * application. With all the states handled and reported back to
- * developer.
- * </p>
- */
- public class AppExternalFileWriter {
- private static final String canNotWriteFile = "Can not write file: ";
- private static final String canNotCreateDirectory = "Can not create directory: ";
- private final File externalStorageDirectory;
- private final File externalCacheDirectory;
- private Context context;
- private File appDirectory;
- private File appCacheDirectory;
- /**
- * Creates external file writer
- *
- * @param context
- * : Context
- */
- public AppExternalFileWriter(Context context) {
- this.context = context;
- externalStorageDirectory = Environment.getExternalStorageDirectory();
- externalCacheDirectory = context.getExternalCacheDir();
- }
- private File createFile(String fileName, boolean inCache)
- throws ExternalFileWriterException {
- return createFile(fileName, getAppDirectory(inCache));
- }
- /**
- * Create a file in the app directory with given file name.
- *
- * @param fileName
- * : Desired name of the file
- * @param parent
- * parent of the file
- *
- * @return : File with desired name
- */
- private File createFile(String fileName, File parent)
- throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- try {
- if (parent.isDirectory()) {
- File detailFile = new File(parent, fileName);
- if (!detailFile.exists())
- detailFile.createNewFile();
- else {
- String messege = "File already there ";
- throwException(messege);
- }
- return detailFile;
- } else {
- throwException(parent + " should be a directory");
- }
- } catch (IOException e) {
- e.printStackTrace();
- String errorMessege = "IOException " + e;
- throwException(errorMessege);
- } catch (Exception e) {
- e.printStackTrace();
- String errorMessege = "Exception " + e;
- throwException(errorMessege);
- }
- }
- return null;
- }
- /** Creates app directory */
- private void createAppDirectory() throws ExternalFileWriterException {
- String directoryName = context
- .getString(context.getApplicationInfo().labelRes);
- if (isExternalStorageAvailable(false)) {
- appDirectory = new File(Environment.getExternalStorageDirectory()
- .toString(), directoryName);
- createDirectory(appDirectory);
- appCacheDirectory = new File(externalCacheDirectory, directoryName);
- createDirectory(appCacheDirectory);
- }
- }
- private double getAvailableSpace() {
- StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
- .getPath());
- double sdAvailSize = (double) stat.getAvailableBlocks()
- * (double) stat.getBlockSize();
- return sdAvailSize;
- }
- private boolean isExternalStorageAvailable(boolean isForFile)
- throws ExternalFileWriterException {
- String errorStarter = (isForFile) ? canNotWriteFile
- : canNotCreateDirectory;
- String storageState = Environment.getExternalStorageState();
- if (storageState.equals(Environment.MEDIA_MOUNTED)) {
- return true;
- } else if (storageState.equals(Environment.MEDIA_BAD_REMOVAL)) {
- throwException(errorStarter
- + "Media was removed before it was unmounted.");
- } else if (storageState.equals(Environment.MEDIA_CHECKING)) {
- throwException(errorStarter
- + "Media is present and being disk-checked, "
- + "Please wait and try after some time");
- } else if (storageState.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
- throwException(errorStarter + "Presented Media is read only");
- } else if (storageState.equals(Environment.MEDIA_NOFS)) {
- throwException(errorStarter + "Blank or unsupported file media");
- } else if (storageState.equals(Environment.MEDIA_SHARED)) {
- throwException(errorStarter
- + "Media is shared with USB mass storage");
- } else if (storageState.equals(Environment.MEDIA_REMOVED)) {
- throwException(errorStarter + "Media is not present");
- } else if (storageState.equals(Environment.MEDIA_UNMOUNTABLE)) {
- throwException(errorStarter
- + "Media is present but cannot be mounted");
- } else if (storageState.equals(Environment.MEDIA_UNMOUNTED)) {
- throwException(errorStarter + "Media is present but not mounted");
- }
- return false;
- }
- private void throwException(String errorMessege)
- throws ExternalFileWriterException {
- throw new ExternalFileWriterException(errorMessege);
- }
- private File createDirectory(File directory)
- throws ExternalFileWriterException {
- if (!directory.exists() || !directory.isDirectory()) {
- if (directory.mkdirs()) {
- String messege = "directory " + directory + " created : Path "
- + directory.getPath();
- System.out.println(messege);
- } else {
- if (directory.exists()) {
- if (directory.isDirectory()) {
- String messege = "directory " + directory
- + " Already exists : Path "
- + directory.getPath();
- System.out.println(messege);
- } else {
- String messege = directory
- + "should be a directory but found a file : Path "
- + directory.getPath();
- throwException(messege);
- System.out.println(messege);
- }
- }
- }
- }
- return directory;
- }
- /**
- * Write byte array to file. Will show error if given file is a directory.
- *
- * @param file
- * : File where data is to be written.
- * @param data
- * String which you want to write a file. If size of this is
- * greater than size available, it will show error.
- */
- private void writeDataToFile(File file, String data)
- throws ExternalFileWriterException {
- byte[] stringBuffer = data.getBytes();
- writeDataToFile(file, stringBuffer);
- }
- /**
- * Write byte array to file. Will show error if given file is a directory.
- *
- * @param file
- * : File where data is to be written.
- * @param data
- * byte array which you want to write a file. If size of this is
- * greater than size available, it will show error.
- */
- private void writeDataToFile(File file, byte[] data)
- throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- if (file.isDirectory()) {
- throwException(file
- + " is not a file, can not write data in it");
- } else {
- if (file != null && data != null) {
- double dataSize = data.length;
- double remainingSize = getAvailableSpace();
- if (dataSize >= remainingSize) {
- throwException("Not enough size available");
- } else {
- try {
- FileOutputStream out = new FileOutputStream(file);
- out.write(data);
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
- private File getAppDirectory(boolean inCache) {
- return (inCache) ? this.appCacheDirectory : this.appDirectory;
- }
- /**
- * Creates subdirectory in application directory
- *
- * @param directoryName
- * name of subdirectory
- *
- * @return File object of created subdirectory
- *
- * @throws ExternalFileWriterException
- * if external storage is not available
- */
- public File createSubDirectory(String directoryName, boolean inCache)
- throws ExternalFileWriterException {
- if (isExternalStorageAvailable(false)) {
- getAppDirectory();
- File subDirectory = new File(getAppDirectory(inCache),
- directoryName);
- return createDirectory(subDirectory);
- } else
- return null;
- }
- /**
- * Checks whether directory with given name exists in AppDirectory
- *
- * @param directoryName
- * : Name of the directory to check.
- *
- * @return true if a directory with "directoryName" exists, false otherwise
- */
- public boolean isDirectoryExists(String directoryName, boolean checkInCache) {
- File parentDirectory = (checkInCache) ? appCacheDirectory
- : appDirectory;
- return isDirectoryExists(directoryName, parentDirectory);
- }
- /**
- * Check whether file with given name exists in parentDirectory or not.
- *
- * @param fileName
- * : Name of the file to check.
- * @param parentDirectory
- * : Parent directory where directory with "fileName" should be
- * present
- *
- * @return true if a file with "fileName" exists, false otherwise
- */
- public boolean isFileExists(String fileName, File parentDirectory) {
- File directoryToCheck = new File(parentDirectory, fileName);
- return directoryToCheck.exists() && directoryToCheck.isFile();
- }
- /**
- * Checks whether file with given name exists in AppDirectory
- *
- * @param fileName
- * : Name of the file to check.
- *
- * @return true if a file with "directoryName" exists, false otherwise
- */
- public boolean isFileExists(String fileName, boolean checkInCache) {
- File parentDirectory = (checkInCache) ? appCacheDirectory
- : appDirectory;
- return isFileExists(fileName, parentDirectory);
- }
- /**
- * Check whether directory with given name exists in parentDirectory or not.
- *
- * @param directoryName
- * : Name of the directory to check.
- * @param parentDirectory
- * : Parent directory where directory with "directoryName" should
- * be present
- *
- * @return true if a directory with "directoryName" exists, false otherwise
- */
- public boolean isDirectoryExists(String directoryName, File parentDirectory) {
- File directoryToCheck = new File(parentDirectory, directoryName);
- return directoryToCheck.exists() && directoryToCheck.isDirectory();
- }
- /**
- * Creates subdirectory in parent directory
- *
- * @param parent
- * : Parent directory where directory with "directoryName" should
- * be created
- * @param directoryName
- * name of subdirectory
- *
- * @return File object of created subdirectory
- *
- * @throws ExternalFileWriterException
- * if external storage is not available
- */
- public File createSubDirectory(File parent, String directoryName)
- throws ExternalFileWriterException {
- if (isExternalStorageAvailable(false)) {
- getAppDirectory();
- if (!parent.isDirectory())
- throwException(parent.getName() + " Must be a directory ");
- File subDirectory = new File(parent, directoryName);
- return createDirectory(subDirectory);
- } else
- return null;
- }
- /**
- * Deletes given directory with all its subdirectories and its files.
- *
- * @param directory
- * : Directory to delete
- */
- public void deleteDirectory(File directory) {
- if (directory != null) {
- if (directory.isDirectory())
- for (File child : directory.listFiles()) {
- if (child != null) {
- if (child.isDirectory())
- deleteDirectory(child);
- else
- child.delete();
- }
- }
- directory.delete();
- }
- // return false;
- }
- /**
- * Get created app directory
- *
- * @return File object of created AppDirectory
- */
- public File getAppDirectory() throws ExternalFileWriterException {
- if (appDirectory == null) {
- createAppDirectory();
- }
- return appDirectory;
- }
- /**
- * get External Cache directory
- *
- * @return File object of External Cache directory
- */
- public File getExternalCacheDirectory() {
- return externalCacheDirectory;
- }
- /**
- * Get external storage directory
- *
- * @return File object of external storage directory
- */
- public File getExternalStorageDirectory() {
- return externalStorageDirectory;
- }
- /**
- * Write data in file of a parent directory
- *
- * @param parent
- * parent directory
- * @param fileName
- * desired filename
- * @param data
- * data
- *
- * @throws ExternalFileWriterException
- * if external storage is not available or free space is less
- * than size of the data
- */
- public void writeDataToFile(File parent, String fileName, byte[] data)
- throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- getAppDirectory();
- File file = createFile(fileName, parent);
- writeDataToFile(file, data);
- }
- }
- /**
- * Writes data to the file. The file will be created in the directory name
- * same as app.
- *
- * @param fileName
- * name of the file
- * @param data
- * data to write
- *
- * @throws ExternalFileWriterException
- * if external storage is not available or free space is less
- * than size of the data
- */
- public void writeDataToFile(String fileName, String data, boolean inCache)
- throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- getAppDirectory();
- File file = createFile(fileName, inCache);
- writeDataToFile(file, data);
- }
- }
- /**
- * Writes data to the file. The file will be created in the directory name
- * same as app.
- *
- * @param fileName
- * name of the file
- * @param data
- * data to write
- *
- * @throws ExternalFileWriterException
- * if external storage is not available or free space is less
- * than size of the data
- */
- public void writeDataToFile(String fileName, byte[] data, boolean inCache)
- throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- getAppDirectory();
- File file = createFile(fileName, inCache);
- writeDataToFile(file, data);
- }
- }
- /**
- * Write data in file of a parent directory
- *
- * @param parent
- * parent directory
- * @param fileName
- * desired filename
- * @param data
- * data
- *
- * @throws ExternalFileWriterException
- * if external storage is not available or free space is less
- * than size of the data
- */
- public void writeDataToFile(File parent, String fileName, String data)
- throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- getAppDirectory();
- File file = createFile(fileName, parent);
- writeDataToFile(file, data);
- }
- }
- /**
- * Writes data to the file. The file will be created in the directory name
- * same as app.
- * <p>
- * Name of the file will be the timestamp.extension
- * </p>
- *
- * @param extension
- * extension of the file, pass null if you don't want to have
- * extension.
- * @param data
- * data to write
- * @param inCache
- * Pass true if you want to write data in External Cache. false
- * if you want to write data in external directory.
- *
- * @throws ExternalFileWriterException
- * if external storage is not available or free space is less
- * than size of the data
- */
- public void writeDataToTimeStampedFile(String extension, String data,
- boolean inCache) throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- getAppDirectory();
- String fileExtension = (TextUtils.isEmpty(extension)) ? "" : "."
- + extension;
- String fileName = System.currentTimeMillis() + fileExtension;
- File file = createFile(fileName, getAppDirectory(inCache));
- writeDataToFile(file, data);
- }
- }
- /**
- * Writes data to the file. The file will be created in the directory name
- * same as app.
- * <p>
- * Name of the file will be the timestamp.extension
- * </p>
- *
- * @param parent
- * parent directory path
- * @param extension
- * extension of the file, pass null if you don't want to have
- * extension.
- * @param data
- * data to write
- *
- * @throws ExternalFileWriterException
- * if external storage is not available or free space is less
- * than size of the data
- */
- public void writeDataToTimeStampedFile(File parent, String extension,
- String data) throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- getAppDirectory();
- String fileExtension = (TextUtils.isEmpty(extension)) ? "" : "."
- + extension;
- String fileName = System.currentTimeMillis() + fileExtension;
- File file = createFile(fileName, parent);
- writeDataToFile(file, data);
- }
- }
- /**
- * Writes data to the file. The file will be created in the directory name
- * same as app.
- * <p>
- * Name of the file will be the timestamp.extension
- * </p>
- *
- * @param extension
- * extension of the file, pass null if you don't want to have
- * extension.
- * @param data
- * data to write
- *
- * @throws ExternalFileWriterException
- * if external storage is not available or free space is less
- * than size of the data
- */
- public void writeDataToTimeStampedFile(String extension, byte[] data,
- boolean inCache) throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- getAppDirectory();
- String fileExtension = (TextUtils.isEmpty(extension)) ? "" : "."
- + extension;
- String fileName = System.currentTimeMillis() + fileExtension;
- File file = createFile(fileName, getAppDirectory(inCache));
- writeDataToFile(file, data);
- }
- }
- /**
- * Writes data to the file. The file will be created in the directory name
- * same as app.
- * <p>
- * Name of the file will be the timestamp.extension
- * </p>
- *
- * @param parent
- * parent directory path
- * @param extension
- * extension of the file, pass null if you don't want to have
- * extension.
- * @param data
- * data to write
- *
- * @throws ExternalFileWriterException
- * if external storage is not available or free space is less
- * than size of the data
- */
- public void writeDataToTimeStampedFile(File parent, String extension,
- byte[] data) throws ExternalFileWriterException {
- if (isExternalStorageAvailable(true)) {
- getAppDirectory();
- String fileExtension = (TextUtils.isEmpty(extension)) ? "" : "."
- + extension;
- String fileName = System.currentTimeMillis() + fileExtension;
- File file = createFile(fileName, parent);
- writeDataToFile(file, data);
- }
- }
- /**
- * Exception to report back developer about media state or storage state if
- * writing is not possible
- */
- public class ExternalFileWriterException extends Exception {
- public ExternalFileWriterException(String messege) {
- super(messege);
- }
- }
- }
在MainActivity.java中使用的方法如下:
- String test = "writer File class test";
- if (testFolder == null) {
- testFolder = writer.getExternalStorageDirectory();// 获取sd卡的根目录,testFolder和writer分别为File和AppExternalFileWriter(this)的实例
- }
- try {
- writer.writeDataToFile(testFolder, "fileName.txt",
- test.getBytes());// 注意对应的惨胡分别为存储目录,写入的文件名称,byte[]
- } catch (ExternalFileWriterException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
注意添加写入的权限:
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
封装一个帮助类来写文件到android外置存储器上的更多相关文章
- 使用libzplay库封装一个音频类
装载请说明原地址,谢谢~~ 前两天我已经封装好一个duilib中使用的webkit内核的浏览器控件和一个基于vlc的用于播放视频的视频控件,这两个控件可以分别用在放酷狗播放器的乐库功能和MV ...
- 1.使用C++封装一个链表类LinkList
使用C++封装一个链表类LinkList.写出相应一个测试用例 链表需要提供 添加 修改删除 除重 合并 排序创建 销毁等接口. 不能调用库函数或者使用STL等类库 题目延伸********** ...
- PHP封装一个通用好用的文件上传处理类
封装一个文件上传类完成基本功能如下: 1.可上传多个或单个文件 2.上传成功返回一个或多个文件名 3.上传失败则返回每个失败文件的错误信息 上传类中的基本功能: 1.构造参数,用户可以自定义配置参数, ...
- 使用Java封装一个DBUtils类(反射)
刚开始学JavaWeb时,我是调用N个setter方法将从数据库中查询出的数据封装成JavaBean的,极其繁琐. 后来了解SpringJDBC后,发现它提供的接口非常简单,然后就想自己封装一个简单的 ...
- Swift - 简单封装一个工具类模板
创建模板类(封装一个类) 例1:新建一个名字叫做 Product 的类 Product.swift File 的内容 class Product { var name: String var desc ...
- 用C#写的一个OA类的APP, ios、Android都能跑,有源代码
这是一个用C#写的OA类APP,功能包含请假.报销.部门管理.签到.IM.文件上传等功能 话不多说,先看视频 视频地址:http://v.youku.com/v_show/id_XMzUwMjQ1Mz ...
- 使用AutoFac实现依赖注入(封装一个注册类)
public class AutoFacBootStrapper { public static void CoreAutoFacInit() { var builder = new Containe ...
- 封装一个 员工类 使用preparedStatement 查询数据 (2) 使用 arrayList 集合
创建 员工=类生成 有参构造 get set 方法 toString 方法 package cn.hph; public class emp1 { //创建员工类的属性 private int id; ...
- 封装一个 员工类 使用preparedStatement 查询数据 (1)
创建员工类 自动生成get set 方法 package cn.hph; public class emp { //定义表中的属性 private int id; private String en ...
随机推荐
- k8s 基础 k8s架构和组件
k8s 的总架构图
- ORA-12504:tns:监听程序在 CONNECT_DATA中未获得SERVICE_NAME
在VS2008中创建一个数据源时,提示以下错误 “ORA-12504:tns:监听程序在 CONNECT_DATA中未获得SERVICE_NAME” 本机安装ORACLE客户端,找出以下路径的文件D: ...
- service使用handler与Activity沟通的两种方法
通过之前的学习,我们知道了在主线程中声明一个handler实例并实现了消息的处理方法之后,我可以在子线程中用此实例向主线程发消息,在处理方法中获取消息并更新UI. 那么,如果我们想用handler在s ...
- nodejs PK php全方位比较PHP的Node.js的优缺点
全方位比较PHP的Node.js的优缺点 http://www.techug.com/php-vs-node-js
- R语言 arules包 apriori()函数中文帮助文档(中英文对照)
apriori(arules) apriori()所属R语言包:arules Mining Associations w ...
- 转:JMeter整合InfluxDB,Grafana让测试结果实时显示
软件版本: apache-jmeter-2.13.tgz grafana-2.1.1-1.x86_64.rpm influxdb-0.8.8-1.x86_64.rpm 虽然官方不在支持influxdb ...
- 18. CTF综合靶机渗透(十一)
靶机描述: SkyDog Con CTF 2016 - Catch Me If You Can 难度:初学者/中级 说明:CTF是虚拟机,在虚拟箱中工作效果最好.下载OVA文件打开虚拟框,然后选择文件 ...
- SNAT端口转发配置
需求说明 在只有外网地址的机器上也能正常访问内网地址 配置过程 环境网络信息 网络名称 网络地址 外网 192.168.200.0/24 (网关:192.168.200.251) 内网 92.0.0. ...
- Java中的Junit单元测试
测试方法必须使用@Test进行修饰 测试方法必须使用public void 进行修饰,不能带任何的参数 新建一个源代码目录来存放我们的测试代码 测试类的包名应该和被测试类的包名一致 测试单元中的每个方 ...
- window 环境下在虚拟机上安装php环境
转发:https://www.cnblogs.com/orangegem/p/7191659.html 安装linux工具 :https://blog.csdn.net/z15732621582/ar ...