Android 應用中,可能會遇到地址信息,往往存於本地會加快數據的加載和查詢,故可考慮本地數據庫的拷貝,txt文件的讀取,excel文件的讀取來實線。
但有時,數據的來源可能是網上的一個請求,將請求結果本地處理後保存至本地文件,再將本地文件放至 asset 目錄下,進行讀取顯示。
以下爲一個文件讀取的工具類:
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
/**
* author :
* time : 2019/3/26
* desc :
*/
public class FileUtils {
/**
* 將字符串寫入到文本文件中
*/
public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
//生成文件夾之後,再生成文件,不然會出錯
makeFilePath(filePath, fileName);
String strFilePath = filePath + fileName;
// 每次寫入時,都換行寫
String strContent = strcontent + "\r\n";
try {
File file = new File(strFilePath);
if (!file.exists()) {
Log.d("TestFile", "Create the file:" + strFilePath);
file.getParentFile().mkdirs();
file.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(file.length());
raf.write(strContent.getBytes());
raf.close();
} catch (Exception e) {
Log.e("TestFile", "Error on write File:" + e);
}
}
/**
* 生成文件
*/
public static File makeFilePath(String filePath, String fileName) {
File file = null;
makeRootDirectory(filePath);
try {
file = new File(filePath + fileName);
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
/**
* 生成文件夾
*/
public static void makeRootDirectory(String filePath) {
File file = null;
try {
file = new File(filePath);
if (!file.exists()) {
file.mkdir();
}
} catch (Exception e) {
Log.i("error:", e + "");
}
}
/**
* 讀取指定目錄下的所有TXT文件的文件內容
*/
public static String getFileContent(File file) {
String content = "";
if (!file.isDirectory()) { //檢查此路徑名的文件是否是一個目錄(文件夾)
if (file.getName().endsWith("txt")) {//文件格式爲""文件
try {
InputStream instream = new FileInputStream(file);
if (instream != null) {
InputStreamReader inputreader
= new InputStreamReader(instream, "UTF-8");
BufferedReader buffreader = new BufferedReader(inputreader);
String line = "";
//分行讀取
while ((line = buffreader.readLine()) != null) {
content += line + "\n";
}
instream.close();//關閉輸入流
}
} catch (java.io.FileNotFoundException e) {
Log.d("TestFile", "The File doesn't not exist.");
} catch (IOException e) {
Log.d("TestFile", e.getMessage());
}
}
}
return content;
}
/**
* 獲取asset 下面文件的內容
*/
public static String getAssetsFile(Context context, String fileName) {
String result = "";
try {
AssetManager am = context.getAssets();
InputStream is = context.getAssets().open(fileName);
int lenght = is.available();
byte[] buffer = new byte[lenght];
is.read(buffer);
result = new String(buffer, "utf8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
另附實用好文一篇:https://blog.csdn.net/greathfs/article/details/52123984