如何在Android中读取文本文件?

时间:2019-04-26 10:36:06

标签: android

我有一个文本文件复制到Android设备。在我的应用程序中,我想浏览文件,阅读并处理它。问题是,我找不到能够可靠地获取文件路径以读取文件的方法。

我使用以下代码启动选择器:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);

try {
    startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {

}

onActivityResult上,我尝试获取路径,并且在不同的设备上观察到不同的行为。

Android 8 设备:

Uri uri = data.getData();
String path = uri.getPath();                //  --> /external_files/info.txt
String fileName = uri.getLastPathSegment(); //  --> info.txt
String absPath = Environment.getExternalStorageDirectory().getAbsolutePath() --> /storage/emulated/0
// /storage/emulated/0/info.txt --> I can open the file with this path

Android 7 设备:

Uri uri = data.getData();
String path = uri.getPath();                 // --> /document/primary:info.txt
String fileName = uri.getLastPathSegment();  // --> primary:info.txt
String absPath = Environment.getExternalStorageDirectory().getAbsolutePath() --> /storage/emulated/0
// /storage/emulated/0/info.txt --> I can open the file with this path

有什么机制可以获取读取文件的路径。

谢谢, GL

3 个答案:

答案 0 :(得分:0)

您可以使用以下代码获取文件内容,而不是获取路径并再次读取:

Uri uri = data.getData();
InputStreamReader inputStreamReader = new InputStreamReader(getContentResolver().openInputStream(uri));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String s;
while ((s = bufferedReader.readLine()) != null) {
    sb.append(s);
}
String fileContent = sb.toString();

请注意,这些行需要包装在try-catch块中,并且不要忘记关闭流。

答案 1 :(得分:0)

您可以从此代码段中读取文件

/**
 * Helper class. Allowing reading data from a file.
 */
public final class FileDataReader {

    /**
     * Read a file line by line. Every line from the file will be a new data emission.
     *
     * @param filename the file being read
     */
    public static Observable<String> readFileByLine(@NonNull final String filename) {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> lineSubscriber) {
                InputStream inputStream = FileDataReader.class.getResourceAsStream(filename);

                if (inputStream == null) {
                    lineSubscriber.onError(new IllegalArgumentException(
                            "File not found on classpath: " + filename));
                    return;
                }

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,
                        Charset.forName("UTF-8")));
                String line;
                try {
                    while ((line = reader.readLine()) != null) {
                        lineSubscriber.onNext(line);
                    }
                    reader.close();
                    // no more lines to read, we can complete our subscriber.
                    lineSubscriber.onCompleted();
                } catch (IOException ex) {
                    lineSubscriber.onError(ex);
                }

            }
        });
    }
}

有关更多详细信息,请查看下面的链接

https://github.com/florina-muntenescu/ReactiveBurgers/blob/master/app/src/main/java/fmuntenescu/reactiveburgers/FileDataReader.java

答案 2 :(得分:0)

在Kotlin中,您应该可以执行以下操作:

val inputStream = context.contentResolver.openInputStream(uri)
val fileContent = inputStream.bufferedReader().use {it.readText()}