项目地址:点击打开

项目简介:写文件到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外置存储器上的更多相关文章

  1. 使用libzplay库封装一个音频类

    装载请说明原地址,谢谢~~      前两天我已经封装好一个duilib中使用的webkit内核的浏览器控件和一个基于vlc的用于播放视频的视频控件,这两个控件可以分别用在放酷狗播放器的乐库功能和MV ...

  2. 1.使用C++封装一个链表类LinkList

     使用C++封装一个链表类LinkList.写出相应一个测试用例 链表需要提供 添加 修改删除 除重 合并 排序创建 销毁等接口. 不能调用库函数或者使用STL等类库 题目延伸********** ...

  3. PHP封装一个通用好用的文件上传处理类

    封装一个文件上传类完成基本功能如下: 1.可上传多个或单个文件 2.上传成功返回一个或多个文件名 3.上传失败则返回每个失败文件的错误信息 上传类中的基本功能: 1.构造参数,用户可以自定义配置参数, ...

  4. 使用Java封装一个DBUtils类(反射)

    刚开始学JavaWeb时,我是调用N个setter方法将从数据库中查询出的数据封装成JavaBean的,极其繁琐. 后来了解SpringJDBC后,发现它提供的接口非常简单,然后就想自己封装一个简单的 ...

  5. Swift - 简单封装一个工具类模板

    创建模板类(封装一个类) 例1:新建一个名字叫做 Product 的类 Product.swift File 的内容 class Product { var name: String var desc ...

  6. 用C#写的一个OA类的APP, ios、Android都能跑,有源代码

    这是一个用C#写的OA类APP,功能包含请假.报销.部门管理.签到.IM.文件上传等功能 话不多说,先看视频 视频地址:http://v.youku.com/v_show/id_XMzUwMjQ1Mz ...

  7. 使用AutoFac实现依赖注入(封装一个注册类)

    public class AutoFacBootStrapper { public static void CoreAutoFacInit() { var builder = new Containe ...

  8. 封装一个 员工类 使用preparedStatement 查询数据 (2) 使用 arrayList 集合

    创建 员工=类生成 有参构造 get set 方法 toString 方法 package cn.hph; public class emp1 { //创建员工类的属性 private int id; ...

  9. 封装一个 员工类 使用preparedStatement 查询数据 (1)

    创建员工类  自动生成get set 方法 package cn.hph; public class emp { //定义表中的属性 private int id; private String en ...

随机推荐

  1. 双向链表、双向循环链表的JS实现

    关于链表简介.单链表.单向循环链表.JS中的使用以及扩充方法:  单链表.循环链表的JS实现 关于四种链表的完整封装: https://github.com/zhuwq585/Data-Structu ...

  2. 关于mysql的几个必知点

    实际运用中遇到的才了解到的 导出sql文件时navicat导出的sql文件形式是一条记录一个insert语句,所以文件会比较大点,后续插入也会比较慢,而用mysqldump命令导出的sql文件会合并插 ...

  3. 纠结于搞.Net待遇不高的同学入...

    最近看到不少抱怨搞.net工资低的帖子.别的方向我不是太清楚,作为搞了近8年.Net信息系统开发的码农也想发表下自己的意见. 由于我的阅历和能力有限,首先想限定下本文的范围.这里说的“信息系统”主要包 ...

  4. java面向对象编程——第八章 类的高级概念

    8.1访问修饰符: public:该类或非该类均可访问: private: 只有该类可以访问: protected:该类及其子类的成员可以访问,同一个包中的类也可以访问: 默认:相同数据包中的类可以访 ...

  5. Professional iOS Network Programming Connecting the Enterprise to the iPhone and iPad

    Book Description Learn to develop iPhone and iPad applications for networked enterprise environments ...

  6. zf-关于即将过期提示字符串的修改

    Struts2中的 addFieldError(str1,str2); 自带输出 str1= [str2] 这样子是自带输出的 但是如果 要把=[]替换掉怎么办呢 当时想的很复杂,现在知道了,其实很简 ...

  7. Zookeeper + Dubbo + SpringMVC + dubbo-admin

    第一步:在CentOS/Windows上安装Zookeeper[前提] A:CentOS     Zookeeper作为Dubbo服务的注册中心,Dubbo原先基于数据库的注册中心,没采用Zookee ...

  8. 简单的纯js三级联动

    参考这个  日尼禾尔  二级联动 写了三级联动 <!DOCTYPE html> <html> <head> <meta charset="UTF-8 ...

  9. 修改linux下yum镜像源为国内镜像

    修改为163yum源-mirrors.163.com 1.首先备份系统自带yum源配置文件/etc/yum.repos.d/CentOS-Base.repo [root@localhost ~]# m ...

  10. [Linux] ubuntu server sudo出现sudo:must be setuid root 完美解决办法

    1.开机按shift或esc先进行recovery模式 2.选择root命令行模式 3.先执行 #mount -o remount,rw / 这个很重要,网上找的很多资料都不全没有这步造成无法恢复成功 ...