android 文件操作类(参考链接)

http://www.cnblogs.com/menlsh/archive/2013/04/02/2997084.html

package com.android.wang.androidstudio;
import org.apache.http.util.EncodingUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter; import java.io.ByteArrayInputStream;
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 java.io.InputStream;
import java.io.OutputStream; /**
* Created by Administrator on 2016/4/29.
*/
public class FileHelper {
private Context context;
private String SDPATH;//SD卡路径
private String FILESPATH;//文件路径
public FileHelper(Context context)
{
this.context= context;
SDPATH= Environment.getExternalStorageDirectory().getPath();
FILESPATH=this.context.getFilesDir().getPath();
}
public boolean SDCardState(){ //判断SD卡是否可读写
if(Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)){//表示SDCard存在并且可以读写
return true;
}else{
return false;
}
}
public String SDCardPath() {//SDCard路径
if (SDCardState()) {
SDPATH = Environment.getExternalStorageDirectory().getPath();
return SDPATH;
} else {
return null;
}
}
@TargetApi(18)
private String GetSDAvailableSize() {//获取SD可用内存大小
long blockSize=0;
long availableBlocks= 0;
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.GINGERBREAD)
{
blockSize = stat.getBlockSizeLong();
availableBlocks = stat.getAvailableBlocksLong();
}
else {
blockSize = stat.getBlockSize();
availableBlocks = stat.getAvailableBlocks();
}
return Formatter.formatFileSize(context, blockSize * availableBlocks);
}
@TargetApi(18)
private String GetSDTotalSize() { //获取SD总内存大小
long blockSize = 0;
long totalBlocks = 0;
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.GINGERBREAD)
{
blockSize = stat.getBlockSizeLong();
totalBlocks = stat.getBlockCountLong();
}
else {
blockSize = stat.getBlockSize();
totalBlocks = stat.getBlockCount();
} return Formatter.formatFileSize(context, blockSize * totalBlocks);
}
@TargetApi(18)
private String getRomTotalSize() {//获取机身可用内存
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return Formatter.formatFileSize(context, blockSize * totalBlocks);
}
@TargetApi(18)
private String getRomAvailableSize() { //获得机身可用内存
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return Formatter.formatFileSize(context, blockSize * availableBlocks);
}
public File CreateDirOnSDCard(String dir)//在SD上创建目录
{
if(SDCardState()==true) {
File dirFile = new File(SDPATH + File.separator + dir + File.separator);
dirFile.mkdirs();//创建多级目录创建单级目录用mkdir();
return dirFile;
}
else
{
return null;
}
}
public File CreateFileOnSDCard(String fileName) throws IOException { //SD上创建文件(在类和方法后面用throws,直接抛出异常就要用到throw) File file = new File(SDPATH + File.separator + fileName);
if (!file.exists()) { file.createNewFile(); }
return file;
}
public File CreateFileOnSDCard(String dir,String fileName) throws IOException { //SD上的文件目录下创建文件(在类和方法后面用throws,直接抛出异常就要用到throw) File file = new File(SDPATH + File.separator + dir + File.separator + fileName);
if (!file.exists()) {
file.createNewFile(); }
return file;
}
public boolean fileIsExists(String strFile)//判断文件是否存在
{
try
{
File f=new File(strFile);
if(!f.exists())
{
return false;
}
}
catch (Exception e)
{
return false;
}
return true;
}
public File CreateDirOnRom(String dir)//在ROM上创建文件目录
{
File dirFile = new File(FILESPATH + File.separator+dir);
dirFile.mkdirs();
return dirFile;
}
public File CreateFileOnRom(String fileName)throws IOException//在ROM上创建文件目录
{
File file = new File(FILESPATH + File.separator + fileName);
if (!file.exists()) {
file.createNewFile();
}
return file;
}
public void deleteFile(File file) { //删除文件或文件目录
if (file.exists()) { // 判断文件是否存在
if (file.isFile()) { // 判断是否是文件
file.delete(); // 删除文件;
} else if (file.isDirectory()) { // 否则如果它是一个目录
File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
this.deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
}
}
file.delete();
} else {
}
}
public static String InputStreamTOString(InputStream in) throws Exception{
int BUFFER_SIZE=4096;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1;
while((count = in.read(data,0,BUFFER_SIZE)) != -1)
outStream.write(data, 0, count); data = null;
return new String(outStream.toByteArray(),"ISO-8859-1");
}
public static InputStream StringTOInputStream(String in) throws Exception{ ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes("ISO-8859-1"));
return is;
}
public File WriteDataToSDCard(String path, String fileName, String str)
{
File file = null;
OutputStream output = null;
try {
InputStream data = StringTOInputStream(str);
CreateDirOnSDCard(path); //创建目录
file = CreateFileOnSDCard(path,fileName ); //创建文件
output = new FileOutputStream(file);
byte buffer[] = new byte[2*1024]; //每次写2K数据
int temp;
while((temp = data.read(buffer)) != -1 )
{
output.write(buffer,0,temp);
}
output.flush();
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
output.close(); //关闭数据流操作
} catch (Exception e2) {
e2.printStackTrace();
}
}
return file;
}
public String ReadSDFile1(String fileName) { StringBuffer sb = new StringBuffer();
File file = new File(SDPATH + File.separator+ fileName);
try {
FileInputStream fis = new FileInputStream(file);
int c;
while ((c = fis.read()) != -1) {
sb.append((char) c);
}
fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
return sb.toString(); }
public String ReadSDFile2(String fileName) { String sb = new String();
File file = new File(SDPATH + "//" + fileName);
try {
FileInputStream fis = new FileInputStream(file);
int length = fis.available();
byte[] buffer = new byte[length];
fis.read(buffer);
sb = EncodingUtils.getString(buffer, "UTF-8");
fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
return sb.toString();
}
//在默认Rom目录下创建文件并写数据(mang.txt,"内容")可在data/data/mang.txt
public void WriteFileOnRom(String fileName,String writestr){
try{
FileOutputStream fout =context.openFileOutput(fileName,context.MODE_PRIVATE);
byte [] bytes = writestr.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
} //读数据
public String ReadFileOnRom(String fileName) {
String res="";
try{
FileInputStream fin = context.openFileInput(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res; }
//写数据到SD中的文件
public void WriteFileSdcardFile(String fileName,String write_str) throws IOException{
try{
fileName=fileName+SDPATH;
FileOutputStream fout = new FileOutputStream(fileName);
byte [] bytes = write_str.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
//读SD中的文件
public String readFileSdcardFile(String fileName) throws IOException{
String res="";
if(SDCardState()==false)
{
res="NO";
return res;
}
try{
FileInputStream fin = new FileInputStream(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
} catch(Exception e){
e.printStackTrace();
}
return res;
}
public String readSDFile(String fileName) throws IOException { File file = new File(fileName);
String res="";
FileInputStream fis = new FileInputStream(file);
int length = fis.available();
byte [] buffer = new byte[length];
fis.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fis.close();
return res;
}
//写文件
public void writeSDFile(String fileName, String write_str) throws IOException{ File file = new File(fileName); FileOutputStream fos = new FileOutputStream(file); byte [] bytes = write_str.getBytes(); fos.write(bytes); fos.close();
}
}

  

android 文件操作类简易总结的更多相关文章

  1. 大过年的,不下班的,上个Android文件操作类(内部存储和sd卡均可)

    package com.kkdiangame.UI.res; import java.io.ByteArrayOutputStream; import java.io.File; import jav ...

  2. Android FileUtils 文件操作类

    系统路径 Context.getPackageName(); // 用于获取APP的所在包目录 Context.getPackageCodePath(); //来获得当前应用程序对应的apk文件的路径 ...

  3. File 文件操作类 大全

    File  文件操作类  大全 许多人都会对文件操作感到很难  我也是  但是一个好的项目中必定会涉及到文件操作的 文件的复制 粘贴  等等等 公司大佬写了 一个文件操作的工具类 感觉还是棒棒的啦   ...

  4. Android文件操作工具类(转)

    Android文件操作工具类(转)  2014/4/3 18:13:35  孤独的旅行家  博客园 这个工具类包含Android应用开发最基本的几个文件操作方法,也是我第一次发博客与大家分享自己写的东 ...

  5. [C#] 常用工具类——文件操作类

    /// <para> FilesUpload:工具方法:ASP.NET上传文件的方法</para> /// <para> FileExists:返回文件是否存在&l ...

  6. 文件操作类CFile

    CFile file; CString str1= L"写入文件成功!"; wchar_t *str2; if (!file.Open(L"Hello.txt" ...

  7. asp.net文件操作类

    /** 文件操作类 **/ #region 引用命名空间 using System; using System.Collections.Generic; using System.Text; usin ...

  8. Ini文件操作类

    /// <summary> /// Ini文件操作类 /// </summary> public class Ini { // 声明INI文件的写操作函数 WritePriva ...

  9. java csv 文件 操作类

    一个CSV文件操作类,功能比较齐全: package tool; import java.io.BufferedReader; import java.io.BufferedWriter; impor ...

随机推荐

  1. document.body.scrollTop与document.documentElement.scrollTop兼容

    这两天在写一个JS的网页右键菜单,在实现菜单定位的时候发现了这个问题:chrome居然不认识document.documentElement.scrollTop! 看前辈们的文章,纷纷表示如果有文档声 ...

  2. ios 常用宏(copy)

    分享一下我现在用的 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 3 ...

  3. poj 2728 Desert King(最优比例生成树)

    #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #i ...

  4. 扑克k,你知道的人物吗?

    在扑克牌中,黑桃K——大卫王(以色列联合王国第二任国王):红桃K——查里曼大帝(法兰克国王,后加冕为罗马人的皇帝):梅花K——亚历山大大帝(马其顿帝国国王):方块K——凯撒大帝(罗马共和国终生执政官) ...

  5. Eclipse 浏览文件插件- OpenExplorer

    http://blog.csdn.net/w709854369/article/details/6599167 EasyExplorer  是一个类似于 Windows Explorer的Eclips ...

  6. php的cURL库介绍

    cURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP.FTP.TELNET等.很多小偷程序都是使用这个函数.最爽的是,PHP也支持 cURL 库.本文将介绍 cURL 的 ...

  7. php Mysql 和Mysqli数据库函数整合

    PHP Mysql和Mysqli数据库函数整合 服务器如果支持mysqli函数将优先mysqli函数进行数据库操作 否则将调用mysql函数进行数据库操作 用法SQL::connect(host,us ...

  8. Android GridView(九宫图)

    GridView跟ListView都是比较常用的多控件布局,而GridView更是实现九宫图的首选! <?xml version="1.0" encoding="u ...

  9. VueJS搭建简单后台管理系统框架 (二) 模拟Ajax数据请求

    开发过程中,免不了需要前台与后台的交互,大部分的交互都是通过Ajax请求来完成,在服务端未完成开发时,前端需要有一个可以模拟Ajax请求的服务器. 在NodeJs环境下,通过配置express可访问的 ...

  10. 使用ConcurrentDictionary实现轻量缓存

    项目中需要用到一个轻量缓存,存储重复使用的数据.在设计中需要考虑:1.做成通用组件,为未来其他模块方法操作结果做准备.2.缓存模块需要接口化,为未来替换使用外部缓存做准备.3.使用默认缓存过期时间,单 ...