掃二維碼與項目經理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流
在Android應用中,讀取本地文件是開發(fā)者經常需要進行的操作,這通常涉及到兩種類型的文件:存儲在設備上的常規(guī)文件(如圖片、音頻和視頻等)和應用程序的數據文件(如SharedPreferences,數據庫等),本篇文章將詳細介紹如何在Android中讀取這兩種類型的本地文件。

1、使用AssetManager
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("example.txt");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
String text = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代碼首先獲取了一個AssetManager的實例,然后通過調用其open方法打開一個名為"example.txt"的文件,接著,它創(chuàng)建了一個字節(jié)數組來存儲從文件中讀取的數據,然后使用InputStream的read方法將數據讀入到這個字節(jié)數組中,它將字節(jié)數組轉換為字符串,如果在這個過程中發(fā)生了任何IOException,那么就會捕獲并打印出這個異常,無論是否發(fā)生異常,最后都會嘗試關閉輸入流。
2、使用FileProvider
如果你的應用針對Android 7.0及以上版本,你可以使用FileProvider來訪問設備的文件系統,以下是一個示例:
Uri fileUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", new File("/path/to/your/file"));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(fileUri, "text/plain");
startActivity(intent);
這段代碼首先通過FileProvider的getUriForFile方法獲取了要訪問的文件的Uri,它創(chuàng)建了一個新的Intent,設置了它的action為Intent.ACTION_VIEW,data為你剛剛獲取的Uri,以及MIME類型為"text/plain",它啟動了這個Intent,注意,你需要在你的AndroidManifest.xml文件中配置一個FileProvider,如下所示:
并且還需要在res/xml目錄下創(chuàng)建一個xml文件(例如file_paths.xml),用于指定哪些路徑可以被你的應用訪問:
1、SharedPreferences的使用
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String mySetting = sharedPreferences.getString("mySetting", "defaultValue"); // 從SharedPreferences獲取值,如果找不到則返回默認值
sharedPreferences.edit().putString("mySetting", "newValue").apply(); // 將新值存入SharedPreferences并立即更新

我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流