如何阅读Android中的文本文件?

问题描述 投票:-1回答:3

我有一个文本文件复制到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

android
3个回答
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块中,并且不要忘记关闭流。


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


0
投票

在Kotlin你应该可以做这样的事情:

val inputStream = context.contentResolver.openInputStream(uri)
val fileContent = inputStream.bufferedReader().use {it.readText()}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.