📜  如何在Android中读取文件?(1)

📅  最后修改于: 2023-12-03 15:24:26.879000             🧑  作者: Mango

如何在Android中读取文件?

在Android开发过程中,文件的读取是常见的操作。Android提供了多种方式来读取文件。下面介绍几种常用的读取文件方式。

1. 通过InputStream读取文件
try {
    InputStream inputStream = context.openFileInput(fileName);
    String content = readStreamToString(inputStream);
    inputStream.close();
    // 处理读取到的文件内容
} catch (IOException e) {
    e.printStackTrace();
}

private String readStreamToString(InputStream inputStream) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
    }
    return stringBuilder.toString();
}
2. 通过BufferedReader读取文件
try {
    BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
    String content = readBufferedReaderToString(bufferedReader);
    bufferedReader.close();
    // 处理读取到的文件内容
} catch (IOException e) {
    e.printStackTrace();
}

private String readBufferedReaderToString(BufferedReader bufferedReader) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
    }
    return stringBuilder.toString();
}
3. 通过FileInputStream读取文件
try {
    FileInputStream fileInputStream = new FileInputStream(fileName);
    byte[] buffer = new byte[fileInputStream.available()];
    fileInputStream.read(buffer);
    fileInputStream.close();
    String content = new String(buffer);
    // 处理读取到的文件内容
} catch (IOException e) {
    e.printStackTrace();
}
4. 通过Scanner读取文件
try {
    Scanner scanner = new Scanner(new FileReader(fileName));
    StringBuilder stringBuilder = new StringBuilder();
    while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine());
    }
    scanner.close();
    String content = stringBuilder.toString();
    // 处理读取到的文件内容
} catch (IOException e) {
    e.printStackTrace();
}

以上是Android中几种常用的读取文件方式,根据实际情况选择适合的方式即可。