Android 读取存储文件代码
时间: 2023-04-05 16:02:31 浏览: 66
您好,以下是 Android 读取存储文件的代码示例:
```
try {
File file = new File(Environment.getExternalStorageDirectory(), "example.txt");
FileInputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
String content = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
```
希望对您有帮助。
相关问题
Android 读取存储本地文件代码
你可以使用以下代码读取本地文件:
```c
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("/sdcard/test.txt", "r"); // 打开文件
if (fp == NULL) {
printf("无法打开文件\n");
return 0;
}
while ((ch = fgetc(fp)) != EOF) { // 逐个字符读取文件内容
printf("%c", ch);
}
fclose(fp); // 关闭文件
return 0;
}
```
其中,`/sdcard/test.txt` 是文件的路径和名称,可以根据实际情况修改。
android 读取和存储json文件代码
你可以使用 Android 中的 JSONObject 和 JSONArray 类来读取和存储 JSON 文件。首先,你需要将 JSON 文件读取到一个字符串中,然后使用 JSONObject 或 JSONArray 类将其解析为 Java 对象。以下是一个示例代码:
读取 JSON 文件:
```
try {
InputStream inputStream = context.getAssets().open("example.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
String jsonString = new String(buffer, "UTF-8");
JSONObject jsonObject = new JSONObject(jsonString);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
```
存储 JSON 文件:
```
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", "value");
String jsonString = jsonObject.toString();
FileOutputStream outputStream = context.openFileOutput("example.json", Context.MODE_PRIVATE);
outputStream.write(jsonString.getBytes());
outputStream.close();
} catch (JSONException | IOException e) {
e.printStackTrace();
}
```