项目地址:点击打开

项目简介:写文件到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. Python数据结构与算法设计(总结篇)

    的确,正如偶像Bruce Eckel所说,"Life is short, you need Python"! 如果你正在考虑学Java还是Python的话,那就别想了,选Pytho ...

  2. 安装yum在ubnutu上

    安装yum在ubnutu上1:首先检测是否安装了build-essential程序包 apt-get install build-essential2.安装yumapt-get install yum ...

  3. 向PCD文件写入点云数据

    博客转载自:http://www.pclcn.org/study/shownews.php?lang=cn&id=83 本小节我们学习如何向PCD文件写入点云数据. 代码 章例2文件夹中,打开 ...

  4. tensorflow第一个例子

    import tensorflow as tf import numpy as np # create data x_data = np.random.rand(100).astype(np.floa ...

  5. 292C Beautiful IP Addresses

    传送门 题目 The problem uses a simplified TCP/IP address model, please read the statement carefully. An I ...

  6. PyQt中从RAM新建QIcon对象 / Create a QIcon from binary data

    一般,QIcon是通过png或ico等图标文件来初始化的,但是如果图标资源已经在内存里了,或者一个zip压缩文件内,可以通过QPixmap作为桥梁,转换为图标. zf = zipfile.ZipFil ...

  7. 8、泛型程序设计与c++标准模板库2.5容器适配器

    容器适配器是用来扩展7中基本容器的,是修改和调整其他类接口的类.他们不提供存放数据的实际数据结构的实现方法,而且容器适配器也不支持迭代器. 1.标准栈容器 使用STL中的标准栈为程序员提供了一层附加的 ...

  8. filter与servlet的比较

    filter与servlet的比较   主要从如下四个方面介绍他们之间的区别:                1.概念.                2.生命周期.                3 ...

  9. UE4简单实现描边高亮效果

    材质文件下载地址: 链接:https://pan.baidu.com/s/10HUmXR_YNMOTF-Cg4ybuUg 提取码:m1my 1. 将材质文件放到Content目录中 2. 在项目中添加 ...

  10. ASP.NET MVC中的 _ViewStart.cshtml文件的作用【摘抄】

    ViewStart 在前面的例子中,每一个视图都是使用Layout 属性来指定它的布局.如果多个视图使用同一个布局,就会产生冗余,并且很难维护. _ViewStart.cshtml 页面可用来消除这种 ...