/**
* 文件操作工具包
*/
public class FileUtils {
/**
* 写文本文件 在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下
*
* @param context
* @param msg
*/
public static void write(Context context, String fileName, String content) {
if (content == null)
content = "";
try {
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取文本文件
*
* @param context
* @param fileName
* @return
*/
public static String read(Context context, String fileName) {
try {
FileInputStream in = context.openFileInput(fileName);
return readInStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
private static String readInStream(FileInputStream inStream) {
try {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[512];
int length = -1;
while ((length = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, length);
}
outStream.close();
inStream.close();
return outStream.toString();
} catch (IOException e) {
Log.i("FileTest", e.getMessage());
}
return null;
}
public static File createFile(String folderPath, String fileName) {
File destDir = new File(folderPath);
if (!destDir.exists()) {
destDir.mkdirs();
}
return new File(folderPath, fileName + fileName);
}
/**
* 向手机写图片
*
* @param buffer
* @param folder
* @param fileName
* @return
*/
public static boolean writeFile(byte[] buffer, String folder,
String fileName) {
boolean writeSucc = false;
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
String folderPath = "";
if (sdCardExist) {
folderPath = Environment.getExternalStorageDirectory()
+ File.separator + folder + File.separator;
} else {
writeSucc = false;
}
File fileDir = new File(folderPath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
File file = new File(folderPath + fileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(buffer);
writeSucc = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();