项目地址:点击打开

项目简介:写文件到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. 【java并发编程艺术学习】(二)第一章 java并发编程的挑战

    章节介绍 主要介绍并发编程时间中可能遇到的问题,以及如何解决. 主要问题 1.上下文切换问题 时间片是cpu分配给每个线程的时间,时间片非常短. cpu通过时间片分配算法来循环执行任务,当前任务执行一 ...

  2. Java 数据类型间的相互转化

    Java中常见基本数据类型包括(String除外[引用]) Date(int year,int month,int day,int hour,int minute,int sec); String 格 ...

  3. Web Form要“jquery”ScriptResourceMapping。请添加一个名为 jquery (区分大小写)的 ScriptResourceMapping。”的解决办法。

    1.先将aspnet.scriptmanager.jquery.dl 复制到bin  (网站根目录下的bin文件夹找不到,看看下面的图片中点击[显示所有文档])  文件夹下.   2.在网站根目录下s ...

  4. Asp.net 实现只能允许一个账号同时只能在一个地方登录

    先上帮助类: /// <summary> /// 单点登录帮助类 /// </summary> public class SSOHelper { /// <summary ...

  5. svn merge和branch 详解

    1.本地Repository的创建 repository的创建很简单,假设我要在D:\TortoiseSVN\TestRepository目录中创建repository,只需右键TestReposit ...

  6. VS编译器中设置 输出窗口 只显示error,不显示warning 要如何配置

    VS编译器中设置 输出窗口 只显示error,不显示warning 要如何配置 在编译大型项目的时候,总是VS编译器的输出窗口总是会出现一堆warning警告,要想在里面找到error错误,要使用鼠标 ...

  7. 1.从GUI到MVC

    GUI(graphic user interface 用户图形界面).GUI编程的目的是提供交互性,并根据用户的操作实时的更新界面.用户的操作是不可预知的鼠标和键盘事件,我们如何保持同步和更新?在上层 ...

  8. 超级台阶 (NYOJ—76)

    很简单的高中数学题,写出来主要是提醒自己,写完递推公式(尤其是公式)一定要检查多遍. #include<stdio.h> #include<string.h> int M; i ...

  9. 实用掌中宝--HTML&CSS常用标签速查手册 PDF扫描版

    实用掌中宝--HTML&CSS常用标签速查手册 内容推荐: 本书第一篇以语法和实例相结合的形式,详细讲解了HTML语言中各个元素及其属性的作用.语法和显示效果:第二篇从CSS基本概念开始,分别 ...

  10. The Largest Generation (25)(BFS)(PAT甲级)

    #include<bits/stdc++.h>using namespace std;int n,m,l,t;int a[1307][137][67];int vis[1307][137] ...