Android读取文件内容
时间: 2023-11-11 13:56:18 浏览: 32
Android读取文件内容有几种方法。如果要读取存放在应用私有目录下的文件,可以使用Activity提供的openFileInput()方法。代码示例为:FileInputStream inStream = openFileInput(fileName)。另外,如果要读取外部存储中的文件,需要添加读取权限 `<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />`,然后可以使用FileInputStream或BufferedReader来读取文件内容。
相关问题
Android打开文件获取文件内容
要在Android中打开文件并获取文件内容,您可以使用以下代码:
```java
// 选择文件
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 1);
// 获取文件内容
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri uri = data.getData();
String filePath = uri.getPath();
try {
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
String fileContent = stringBuilder.toString();
// 处理文件内容
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码使用 `Intent.ACTION_GET_CONTENT` 打开文件选择器,让用户选择要打开的文件。然后,通过读取文件内容的方式获取文件内容。
Android studio 读取txt文件内容
你可以使用以下代码来读取txt文件的内容:
```java
try {
InputStream is = getAssets().open("file.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
} catch (IOException ex) {
ex.printStackTrace();
}
```
这段代码会从assets文件夹中读取名为file.txt的文件,并将其内容存储在一个字符串变量中。你可以根据需要修改文件名和路径。请注意,这段代码需要在Activity或Fragment中运行,因为它使用了getAssets()方法。如果你在非Activity或Fragment的类中使用此代码,请传递Context参数并使用context.getAssets()。