文件工具類

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;


/**
 * 文件工具類
 * @version 1.0
 */
public class ToolFile {


private static final String TAG = ToolFile.class.getSimpleName();


/**
* 檢查是否已掛載SD卡鏡像(是否存在SD卡)

* @return
*/
public static boolean isMountedSDCard() {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
return true;
} else {
Log.w(TAG, "SDCARD is not MOUNTED !");
return false;
}
}


/**
* 獲取SD卡剩餘容量(單位Byte)

* @return
*/
public static long gainSDFreeSize() {
if (isMountedSDCard()) {
// 取得SD卡文件路徑
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
// 獲取單個數據塊的大小(Byte)
long blockSize = sf.getBlockSize();
// 空閒的數據塊的數量
long freeBlocks = sf.getAvailableBlocks();


// 返回SD卡空閒大小
return freeBlocks * blockSize; // 單位Byte
} else {
return 0;
}
}


/**
* 獲取SD卡總容量(單位Byte)

* @return
*/
public static long gainSDAllSize() {
if (isMountedSDCard()) {
// 取得SD卡文件路徑
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
// 獲取單個數據塊的大小(Byte)
long blockSize = sf.getBlockSize();
// 獲取所有數據塊數
long allBlocks = sf.getBlockCount();
// 返回SD卡大小(Byte)
return allBlocks * blockSize;
} else {
return 0;
}
}


/**
* 獲取可用的SD卡路徑(若SD卡不沒有掛載則返回"")

* @return
*/
public static String gainSDCardPath() {
if (isMountedSDCard()) {
File sdcardDir = Environment.getExternalStorageDirectory();
if (!sdcardDir.canWrite()) {
Log.w(TAG, "SDCARD can not write !");
}
return sdcardDir.getPath();
}
return "";
}


/**
* 以行爲單位讀取文件內容,一次讀一整行,常用於讀面向行的格式化文件
* @param filePath 文件路徑
*/
public static String readFileByLines(String filePath) throws IOException
{
BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
try
{
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),System.getProperty("file.encoding")));
String tempString = null;
while ((tempString = reader.readLine()) != null)
{
sb.append(tempString);
sb.append("\n");
}
reader.close();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (reader != null){reader.close();}
}


return sb.toString();


}

/**
* 以行爲單位讀取文件內容,一次讀一整行,常用於讀面向行的格式化文件
* @param filePath 文件路徑
* @param encoding 寫文件編碼
*/
public static String readFileByLines(String filePath,String encoding) throws IOException
{
BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
try
{
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),encoding));
String tempString = null;
while ((tempString = reader.readLine()) != null)
{
sb.append(tempString);
sb.append("\n");
}
reader.close();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (reader != null){reader.close();}
}


return sb.toString();
}


/**
* 保存內容
* @param filePath 文件路徑
* @param content 保存的內容
* @throws IOException
*/
public static void saveToFile(String filePath,String content) throws IOException
{
saveToFile(filePath,content,System.getProperty("file.encoding"));
}


/**
* 指定編碼保存內容
* @param filePath 文件路徑
* @param content 保存的內容
* @param encoding 寫文件編碼
* @throws IOException
*/
public static void saveToFile(String filePath,String content,String encoding) throws IOException
{
BufferedWriter writer = null;
File file = new File(filePath);
try
{
if(!file.getParentFile().exists())
{
file.getParentFile().mkdirs();
}
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), encoding));
writer.write(content);


} finally
{
if (writer != null){writer.close();}
}
}

/**
* 追加文本
* @param content 需要追加的內容
* @param file 待追加文件源
* @throws IOException
*/
public static void appendToFile(String content, File file) throws IOException
{
appendToFile(content, file, System.getProperty("file.encoding"));
}


/**
* 追加文本
* @param content 需要追加的內容
* @param file 待追加文件源
* @param encoding 文件編碼
* @throws IOException
*/
public static void appendToFile(String content, File file, String encoding) throws IOException
{
BufferedWriter writer = null;
try
{
if(!file.getParentFile().exists())
{
file.getParentFile().mkdirs();
}
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), encoding));
writer.write(content);
} finally
{
if (writer != null){writer.close();}
}
}

/**
* 判斷文件是否存在
* @param filePath 文件路徑
* @return 是否存在
* @throws Exception
*/
public static Boolean isExsit(String filePath)
{
Boolean flag = false ;
try
{
File file = new File(filePath);
if(file.exists())
{
flag = true;
}
}catch(Exception e){
System.out.println("判斷文件失敗-->"+e.getMessage()); 


return flag;
}

/**
* 快速讀取程序應用包下的文件內容

* @param context
*            上下文
* @param filename
*            文件名稱
* @return 文件內容
* @throws IOException
*/
public static String read(Context context, String filename) throws IOException {
FileInputStream inStream = context.openFileInput(filename);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
return new String(data);
}


/**
* 讀取指定目錄文件的文件內容

* @param fileName
*            文件名稱
* @return 文件內容
* @throws Exception
*/
public static String read(String fileName) throws IOException {
FileInputStream inStream = new FileInputStream(fileName);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
return new String(data);
}


/***
* 以行爲單位讀取文件內容,一次讀一整行,常用於讀面向行的格式化文件

* @param fileName
*            文件名稱
* @param encoding
*            文件編碼
* @return 字符串內容
* @throws IOException
*/
public static String read(String fileName, String encoding)
throws IOException {
BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(fileName), encoding));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
sb.append(tempString);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}


return sb.toString();
}


/**
* 讀取raw目錄的文件內容

* @param context
*            內容上下文
* @param rawFileId
*            raw文件名id
* @return
*/
public static String readRawValue(Context context, int rawFileId) {
String result = "";
try {
InputStream is = context.getResources().openRawResource(rawFileId);
int len = is.available();
byte[] buffer = new byte[len];
is.read(buffer);
result = new String(buffer, "UTF-8");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}


/**
* 讀取assets目錄的文件內容

* @param context
*            內容上下文
* @param fileName
*            文件名稱,包含擴展名
* @return
*/
public static String readAssetsValue(Context context, String fileName) {
String result = "";
try {
InputStream is = context.getResources().getAssets().open(fileName);
int len = is.available();
byte[] buffer = new byte[len];
is.read(buffer);
result = new String(buffer, "UTF-8");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

/**
* 讀取assets目錄的文件內容

* @param context
*            內容上下文
* @param fileName
*            文件名稱,包含擴展名
* @return
*/
public static List<String> readAssetsListValue(Context context, String fileName) {
List<String> list = new ArrayList<String>();
try {
InputStream in = context.getResources().getAssets().open(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
String str = null;
while ((str = br.readLine()) != null) {
list.add(str);
}


} catch (IOException e) {
e.printStackTrace();
}
return list;
}


/**
* 獲取SharedPreferences文件內容

* @param context
*            上下文
* @param fileNameNoExt
*            文件名稱(不用帶後綴名)
* @return
*/
public static Map<String, ?> readShrePerface(Context context,String fileNameNoExt) {
SharedPreferences preferences = context.getSharedPreferences(
fileNameNoExt, Context.MODE_PRIVATE);
return preferences.getAll();
}


/**
* 寫入SharedPreferences文件內容

* @param context
*            上下文
* @param fileNameNoExt
*            文件名稱(不用帶後綴名)
* @param values
*            需要寫入的數據Map(String,Boolean,Float,Long,Integer)
* @return
*/
public static void writeShrePerface(Context context, String fileNameNoExt,Map<String, ?> values) {
try {
SharedPreferences preferences = context.getSharedPreferences(fileNameNoExt, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
for (Iterator iterator = values.entrySet().iterator(); iterator.hasNext();) 
{
Map.Entry<String, ?> entry = (Map.Entry<String, ?>) iterator.next();
if (entry.getValue() instanceof String) {
editor.putString(entry.getKey(), (String) entry.getValue());
} else if (entry.getValue() instanceof Boolean) {
editor.putBoolean(entry.getKey(),(Boolean) entry.getValue());
} else if (entry.getValue() instanceof Float) {
editor.putFloat(entry.getKey(), (Float) entry.getValue());
} else if (entry.getValue() instanceof Long) {
editor.putLong(entry.getKey(), (Long) entry.getValue());
} else if (entry.getValue() instanceof Integer) {
editor.putInt(entry.getKey(),(Integer) entry.getValue());
}
}
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 寫入應用程序包files目錄下文件

* @param context
*            上下文
* @param fileName
*            文件名稱
* @param content
*            文件內容
*/
public static void write(Context context, String fileName, String content) {
try {


FileOutputStream outStream = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
outStream.write(content.getBytes());
outStream.close();


} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 寫入應用程序包files目錄下文件

* @param context
*            上下文
* @param fileName
*            文件名稱
* @param content
*            文件內容
*/
public static void write(Context context, String fileName, byte[] content) {
try {


FileOutputStream outStream = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
outStream.write(content);
outStream.close();


} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 寫入應用程序包files目錄下文件

* @param context
*            上下文
* @param fileName
*            文件名稱
* @param modeType
*            文件寫入模式(Context.MODE_PRIVATE、Context.MODE_APPEND、Context.
*            MODE_WORLD_READABLE、Context.MODE_WORLD_WRITEABLE)
* @param content
*            文件內容
*/
public static void write(Context context, String fileName, byte[] content,
int modeType) {
try {


FileOutputStream outStream = context.openFileOutput(fileName,
modeType);
outStream.write(content);
outStream.close();


} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 指定編碼將內容寫入目標文件

* @param target
*            目標文件
* @param content
*            文件內容
* @param encoding
*            寫入文件編碼
* @throws Exception
*/
public static void write(File target, String content, String encoding)
throws IOException {
BufferedWriter writer = null;
try {
if (!target.getParentFile().exists()) {
target.getParentFile().mkdirs();
}
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(target, false), encoding));
writer.write(content);


} finally {
if (writer != null) {
writer.close();
}
}
}

/**
* 指定目錄寫入文件內容
* @param filePath 文件路徑+文件名
* @param content 文件內容
* @throws IOException
*/
public static void write(String filePath, byte[] content)
throws IOException {
FileOutputStream fos = null;


try {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
fos.write(content);
fos.flush();
} finally {
if (fos != null) {
fos.close();
}
}
}

/**
* 寫入文件

* @param inputStream下載文件的字節流對象
* @param filePath文件的存放路徑(帶文件名稱)
* @throws IOException 
*/
public static File write(InputStream inputStream, String filePath) throws IOException {
OutputStream outputStream = null;
// 在指定目錄創建一個空文件並獲取文件對象
File mFile = new File(filePath);
if (!mFile.getParentFile().exists())
mFile.getParentFile().mkdirs();
try {
outputStream = new FileOutputStream(mFile);
byte buffer[] = new byte[4 * 1024];
int lenght = 0 ;
while ((lenght = inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,lenght);
}
outputStream.flush();
return mFile;
} catch (IOException e) {
Log.e(TAG, "寫入文件失敗,原因:"+e.getMessage());
throw e;
}finally{
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
}
}
}

/**
* 指定目錄寫入文件內容
* @param filePath 文件路徑+文件名
* @param content 文件內容
* @throws IOException
*/
public static void saveAsJPEG(Bitmap bitmap,String filePath)
throws IOException {
FileOutputStream fos = null;


try {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,fos);
fos.flush();
} finally {
if (fos != null) {
fos.close();
}
}
}

/**
* 指定目錄寫入文件內容
* @param filePath 文件路徑+文件名
* @param content 文件內容
* @throws IOException
*/
public static void saveAsPNG(Bitmap bitmap,String filePath)
throws IOException {
FileOutputStream fos = null;


try {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100,fos);
fos.flush();
} finally {
if (fos != null) {
fos.close();
}
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章