逝去的青春
安卓开发学习,一个创建文件,删除文件,读取文件,写入文件的类
2013-6-15 jao
以下就是源码,我花了一个下午,我晕死
 
package com.jao.printlogcat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;

import android.content.Context;
import android.os.Environment;



public class FileHelper {



private Context context;

/** SD卡是否存在**/

private boolean hasSD = false;

/** SD卡的路径**/

private String SDPATH;

/** 当前程序包的路径**/

private String FILESPATH;



public FileHelper(Context context) {

this.context = context;

hasSD = Environment.getExternalStorageState().equals(

android.os.Environment.MEDIA_MOUNTED);

SDPATH = Environment.getExternalStorageDirectory().getPath();

FILESPATH = this.context.getFilesDir().getPath();

}



/**

* 在SD卡上创建文件

*

* @throws IOException

*/

public File createSDFile(String fileName) throws IOException {

File file = new File(SDPATH + "//" + fileName);

if (!file.exists()) {

file.createNewFile();

}

return file;

}



/**

* 删除SD卡上的文件

*

* @param fileName

*/

public boolean deleteSDFile(String fileName) {

File file = new File(SDPATH + "//" + fileName);

if (file == null || !file.exists() || file.isDirectory())

return false;

return file.delete();

}

/**
* 向SD卡中写入文本文件
* @param fileName
*
* @return
*
**/
public String writeSDFile(String fileName, String str){
File file = new File(SDPATH + "//" + fileName);

try {
FileWriter fis = new FileWriter(file);
fis.write(str);
fis.close();
} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return str;
}
/**

* 读取SD卡中文本文件

*

* @param fileName

* @return

*/

public String readSDFile(String fileName) {

StringBuffer sb = new StringBuffer();

File file = new File(SDPATH + "//" + fileName);

try {

FileReader fis = new FileReader(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 getFILESPATH() {

return FILESPATH;

}



public String getSDPATH() {

return SDPATH;

}



public boolean hasSD() {

return hasSD;

}

}



评论:
耐火水泥
2013-07-04 18:19 回复
马克下文章,慢慢看;忠实粉丝,期待更新。我是怡怡,回访一下吧。。。