Android之文件讀寫工具類
本類主要功能有:
1.創建文件功能;
2.向文件中寫入字節數組;
3.向文件中寫入字符串;
4.從文件中讀取字節數組;
5.從文件中讀取字符串;
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream;/**
- 文件讀寫工具類
@author bear / public class FileUtil {
/**
- 如果文件不存在,就創建文件
- @param path 文件路徑
@return */ public static String createIfNotExist(String path) { File file = new File(path); if (!file.exists()) {
try { file.createNewFile(); } catch (Exception e) { System.out.println(e.getMessage()); }
} return path; }
/**
- 向文件中寫入數據
- @param filePath
- 目標文件全路徑
- @param data
- 要寫入的數據
@return 0表示成功寫入,1表示沒找到文件,2表示IO異常 */ public static boolean writeBytes(String filePath, byte[] data) { try {
FileOutputStream fos = new FileOutputStream(filePath); fos.write(data); fos.close(); return true;
} catch (Exception e) {
System.out.println(e.getMessage());
} return false; }
/**
- 從文件中讀取數據
- @param file
@return */ public static byte[] readBytes(String file) { try {
FileInputStream fis = new FileInputStream(file); int len = fis.available(); byte[] buffer = new byte[len]; fis.read(buffer); fis.close(); return buffer;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
/**
- 向文件中寫入字符串String類型的內容
- @param file
- 文件路徑
- @param content
- 文件內容
- @param charset
寫入時候所使用的字符集 */ public static void writeString(String file, String content, String charset) { try { byte[] data = content.getBytes(charset); writeBytes(file, data); } catch (Exception e) { System.out.println(e.getMessage()); }
}
/**
- 從文件中讀取數據,返回類型是字符串String類型
- @param file
- 文件路徑
- @param charset
- 讀取文件時使用的字符集,如utf-8、GBK等
@return */ public static String readString(String file, String charset) { byte[] data = readBytes(file); String ret = null;
try {
ret = new String(data, charset);
} catch (Exception e) {
System.out.println(e.getMessage());
} return ret; }
}</pre>