android 读取本地txt json
时间: 2023-08-16 20:09:07 浏览: 72
android json读取
可以使用以下代码读取本地的txt或json文件:
```java
public String readFromFile(Context context, String fileName) {
String result = "";
try {
InputStream inputStream = context.openFileInput(fileName);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String tempString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((tempString = bufferedReader.readLine()) != null) {
stringBuilder.append(tempString);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
result = stringBuilder.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
```
其中,context参数是上下文对象,fileName是文件名,包括扩展名。如果是在assets文件夹中的文件,则需要使用以下代码读取:
```java
public String readFromAssets(Context context, String fileName) {
String result = "";
try {
InputStream inputStream = context.getAssets().open(fileName);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String tempString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((tempString = bufferedReader.readLine()) != null) {
stringBuilder.append(tempString);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
result = stringBuilder.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
```
使用方法:
```java
String txtData = readFromFile(this, "data.txt"); // 读取本地txt文件
String jsonData = readFromAssets(this, "data.json"); // 读取assets文件夹中的json文件
```
需要注意的是,在使用openFileInput()方法打开文件时,文件应该存储在/data/data/包名/files目录下。如果要读取其他目录下的文件,可以使用FileInputStream或者RandomAccessFile类。
阅读全文