新聞中心
簡介
在Android應(yīng)用中,讀取本地文件是開發(fā)者經(jīng)常需要進行的操作,這通常涉及到兩種類型的文件:存儲在設(shè)備上的常規(guī)文件(如圖片、音頻和視頻等)和應(yīng)用程序的數(shù)據(jù)文件(如SharedPreferences,數(shù)據(jù)庫等),本篇文章將詳細介紹如何在Android中讀取這兩種類型的本地文件。

讀取常規(guī)文件
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的實例,然后通過調(diào)用其open方法打開一個名為"example.txt"的文件,接著,它創(chuàng)建了一個字節(jié)數(shù)組來存儲從文件中讀取的數(shù)據(jù),然后使用InputStream的read方法將數(shù)據(jù)讀入到這個字節(jié)數(shù)組中,它將字節(jié)數(shù)組轉(zhuǎn)換為字符串,如果在這個過程中發(fā)生了任何IOException,那么就會捕獲并打印出這個異常,無論是否發(fā)生異常,最后都會嘗試關(guān)閉輸入流。
2、使用FileProvider
如果你的應(yīng)用針對Android 7.0及以上版本,你可以使用FileProvider來訪問設(shè)備的文件系統(tǒng),以下是一個示例:
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,設(shè)置了它的action為Intent.ACTION_VIEW,data為你剛剛獲取的Uri,以及MIME類型為"text/plain",它啟動了這個Intent,注意,你需要在你的AndroidManifest.xml文件中配置一個FileProvider,如下所示:
并且還需要在res/xml目錄下創(chuàng)建一個xml文件(例如file_paths.xml),用于指定哪些路徑可以被你的應(yīng)用訪問:
讀取應(yīng)用程序的數(shù)據(jù)文件
1、SharedPreferences的使用
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String mySetting = sharedPreferences.getString("mySetting", "defaultValue"); // 從SharedPreferences獲取值,如果找不到則返回默認值
sharedPreferences.edit().putString("mySetting", "newValue").apply(); // 將新值存入SharedPreferences并立即更新
網(wǎng)頁標題:android讀取本地文件的方法是什么
轉(zhuǎn)載注明:http://www.dlmjj.cn/article/dhiejid.html


咨詢
建站咨詢
