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.youkuaiyun.com/greathfs/article/details/52123984