Android手機檔案系統操作——輕鬆儲存與獲取手機檔案
阿新 • • 發佈:2019-02-20
Android獲取各種系統路徑的方法
通過Environment獲取的
- Environment.getDataDirectory().getPath() : 獲得根目錄/data 內部儲存路徑
- Environment.getDownloadCacheDirectory().getPath() : 獲得快取目錄/cache
- Environment.getExternalStorageDirectory().getPath(): 獲得SD卡目錄/mnt/sdcard(獲取的是手機外接sd卡的路徑)
- Environment.getRootDirectory().getPath() : 獲得系統目錄/system
通過Context獲取的
- Context.getDatabasePath() 返回通過Context.openOrCreateDatabase 建立的資料庫檔案
Context.getCacheDir().getPath() : 用於獲取APP的cache目錄/data/data//cache目錄
Context.getExternalCacheDir().getPath() : 用於獲取APP的在SD卡中的cache目錄/mnt/sdcard/
Context.getFilesDir().getPath() : 用於獲取APP的files目錄 /data/data//files
Context.getObbDir().getPath(): 用於獲取APPSDK中的obb目錄/mnt/sdcard/Android/obb/
Context.getPackageName() : 用於獲取APP的所在包目錄
- Context.getPackageCodePath() : 來獲得當前應用程式對應的 apk 檔案的路徑
- Context.getPackageResourcePath() : 獲取該程式的安裝包路徑
完整 操作手機檔案 工具類:
public void saveToPhone(View v) {
// FileDir();
SDCardTest();
}
private void FileDir() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
Log.i("codecraeer", "getFilesDir = " + getFilesDir());
Log.i("codecraeer", "getExternalFilesDir = " + getExternalFilesDir("exter_test").getAbsolutePath());
Log.i("codecraeer", "getDownloadCacheDirectory = " + Environment.getDownloadCacheDirectory().getAbsolutePath());
Log.i("codecraeer", "getDataDirectory = " + Environment.getDataDirectory().getAbsolutePath());
Log.i("codecraeer", "getExternalStorageDirectory = " + Environment.getExternalStorageDirectory().getAbsolutePath());
Log.i("codecraeer", "getExternalStoragePublicDirectory = " + Environment.getExternalStoragePublicDirectory("pub_test"));
}
/**
* SDcard操作
*/
public void SDCardTest(){
try {
//獲取擴充套件SD卡裝置狀態
String sDStateString = Environment.getExternalStorageState();
//擁有可讀可寫許可權
if(sDStateString.equals(Environment.MEDIA_MOUNTED)){
//獲取擴充套件儲存裝置的檔案目錄
File SDFile = Environment.getExternalStorageDirectory();
String fileDirectoryPath=SDFile.getAbsolutePath()+File.separator+"測試資料夾";
File fileDirectory=new File(fileDirectoryPath);
//開啟檔案
File myFile = new File(fileDirectoryPath+File.separator+"MyFile.txt");
//判斷是否存在,不存在則建立
if (!fileDirectory.exists()) {
//按照指定的路徑建立資料夾
fileDirectory.mkdirs();
}
if (!myFile.exists()) {
try {
//在指定的資料夾中建立檔案
myFile.createNewFile();
} catch (Exception e) {
}
}
//寫資料
String szOutText="Hello, World!+姚佳偉";
FileOutputStream outputStream=new FileOutputStream(myFile);
outputStream.write(szOutText.getBytes());
outputStream.close();
}
//擁有隻讀許可權
else if(sDStateString.endsWith(Environment.MEDIA_MOUNTED_READ_ONLY)){
//獲取擴充套件儲存裝置的檔案目錄
File SDFile=android.os.Environment.getExternalStorageDirectory();
//建立一個檔案
File myFile=new File(SDFile.getAbsolutePath()+File.separator+"MyFile.txt");
//判斷檔案是否存在
if(myFile.exists()){
//讀資料
FileInputStream inputStream=new FileInputStream(myFile);
byte[]buffer=new byte[1024];
inputStream.read(buffer);
inputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
Log.d("yjw","檢查許可權");
}
}
public class FileUtils {
static String directoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "FileDemo" + File.separator;
String fileName = directoryPath + getISO8601TimeFileName() + ".txt";
//建立資料夾及檔案
public void CreateText() throws IOException {
File file = new File(directoryPath);
if (!file.exists()) {
try {
//按照指定的路徑建立資料夾
file.mkdirs();
} catch (Exception e) {
// TODO: handle exception
}
}
File dir = new File(fileName);
if (!dir.exists()) {
try {
//在指定的資料夾中建立檔案
dir.createNewFile();
} catch (Exception e) {
}
}
}
//向已建立的檔案中寫入資料
public void print(String str) {
FileWriter fw = null;
BufferedWriter bw = null;
String datetime = "";
try {
CreateText();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd" + " " + "hh:mm:ss");
datetime = tempDate.format(new java.util.Date()).toString();
fw = new FileWriter(fileName, true);//
// 建立FileWriter物件,用來寫入字元流
/**
* 如果想要每次寫入,清除之前的內容,使用FileOutputStream流
*/
bw = new BufferedWriter(fw); // 將緩衝對檔案的輸出
String myreadline = datetime + "[]" + str;
bw.write(myreadline + "\n"); // 寫入檔案
bw.newLine();
bw.flush(); // 重新整理該流的緩衝
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
try {
bw.close();
fw.close();
} catch (IOException e1) {
}
}
}
/**
* 此方法為android程式寫入sd檔案檔案,用到了android-annotation的支援庫@
*
* @param buffer 寫入檔案的內容
* @param folder 儲存檔案的資料夾名稱,如log;可為null,預設儲存在sd卡根目錄
* @param fileName 檔名稱,預設app_log.txt
* @param append 是否追加寫入,true為追加寫入,false為重寫檔案
* @param autoLine 針對追加模式,true為增加時換行,false為增加時不換行
*/
public synchronized static void writeFiledToSDCard(@NonNull final byte[] buffer, @Nullable final String folder, @Nullable final String fileName, final boolean append, final boolean autoLine) {
new Thread(new Runnable() {
@Override
public void run() {
boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
String folderPath = "";
if (sdCardExist) {
//TextUtils為android自帶的幫助類
if (TextUtils.isEmpty(folder)) {
//如果folder為空,則直接儲存在sd卡的根目錄
// folderPath = Environment.getExternalStorageDirectory() + File.separator;
folderPath = directoryPath;
} else {
folderPath = Environment.getExternalStorageDirectory() + File.separator + folder + File.separator;
}
} else {
return;
}
File fileDir = new File(folderPath);
if (!fileDir.exists()) {
if (!fileDir.mkdirs()) {
return;
}
}
File file;
//判斷檔名是否為空
if (TextUtils.isEmpty(fileName)) {
file = new File(folderPath + getISO8601TimeFileName() + ".txt");
} else {
file = new File(folderPath + fileName);
}
RandomAccessFile raf = null;
FileOutputStream out = null;
try {
if (append) {
//如果為追加則在原來的基礎上繼續寫檔案
raf = new RandomAccessFile(file, "rw");
raf.seek(file.length());
raf.write(buffer);
if (autoLine) {
raf.write("\n".getBytes());
}
} else {
//重寫檔案,覆蓋掉原來的資料
out = new FileOutputStream(file);
out.write(buffer);
out.flush();
}
Log.d("yjw", "writeFiledToSDCard===" + "檔案存入成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (raf != null) {
raf.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
public static String getISO8601TimeFileName() {
TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
return nowAsISO;
}
}