如何从 Android 中的 SD 卡读取文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2902689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:49:02  来源:igfitidea点击:

How can I read a text file from the SD card in Android?

androidandroid-sdcard

提问by RSSS

I am new to Android development.

我是 Android 开发的新手。

I need to read a text file from the SD card and display that text file. Is there any way to view a text file directly in Android or else how can I read and display the contents of a text file?

我需要从 SD 卡读取文本文件并显示该文本文件。有什么方法可以直接在 Android 中查看文本文件,或者如何读取和显示文本文件的内容?

回答by Dave Webb

In your layoutyou'll need something to display the text. A TextViewis the obvious choice. So you'll have something like this:

在您的布局中,您需要一些东西来显示文本。ATextView是显而易见的选择。所以你会有这样的事情:

<TextView 
    android:id="@+id/text_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/>

And your code will look like this:

您的代码将如下所示:

//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text);

This could go in the onCreate()method of your Activity, or somewhere else depending on just what it is you want to do.

这可能会出现在onCreate()你的方法中Activity,或者其他地方,这取决于你想要做什么。

回答by Sibbs Gambling

In response to

回应

Don't hardcode /sdcard/

不要硬编码 /sdcard/

Sometimes we HAVE TOhardcode it as in some phone models the API method returns the internal phone memory.

有时候,我们不得不硬编码在某些型号的手机API方法返回内部手机内存。

Known types: HTC One X and Samsung S3.

已知类型:HTC One X 和三星 S3。

Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android

Environment.getExternalStorageDirectory().getAbsolutePath() 给出了不同的路径 - Android

回答by mralien12

You should have READ_EXTERNAL_STORAGE permission for reading sdcard. Add permission in manifest.xml

您应该具有读取 sdcard 的 READ_EXTERNAL_STORAGE 权限。在 manifest.xml 中添加权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link Permissions overview

从 android 6.0 或更高版本开始,您的应用程序必须要求用户在运行时授予危险权限。请参阅此链接 权限概述

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
    }
}

回答by vikseln

package com.example.readfilefromexternalresource;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView)findViewById(R.id.textView);
        String state = Environment.getExternalStorageState();

        if (!(state.equals(Environment.MEDIA_MOUNTED))) {
            Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();


        } else {
            BufferedReader reader = null;
            try {
                Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show();
                File file = Environment.getExternalStorageDirectory();
                File textFile = new File(file.getAbsolutePath()+File.separator + "chapter.xml");
                reader = new BufferedReader(new FileReader(textFile));
                StringBuilder textBuilder = new StringBuilder();
                String line;
                while((line = reader.readLine()) != null) {
                    textBuilder.append(line);
                    textBuilder.append("\n");

                }
                textView.setText(textBuilder);

            } catch (FileNotFoundException e) {
                // TODO: handle exception
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally{
                if(reader != null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}

回答by RSH

BufferedReader br = null;
try {
        String fpath = Environment.getExternalStorageDirectory() + <your file name>;
        try {
            br = new BufferedReader(new FileReader(fpath));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        String line = "";
        while ((line = br.readLine()) != null) {
         //Do something here 
        }

回答by eric stockman

Beware: some phones have 2 sdcards , an internal fixed one and a removable card. You can find the name of the last one via a standard app:"Mijn Bestanden" ( in English: "MyFiles" ? ) When I open this app (item:all files) the path of the open folder is "/sdcard" ,scrolling down there is an entry "external-sd" , clicking this opens the folder "/sdcard/external_sd/" . Suppose I want to open a text-file "MyBooks.txt" I would use something as :

注意:有些手机有 2 个 sdcard,一个内部固定的和一个可移动的卡。您可以通过标准应用程序找到最后一个的名称:“Mijn Bestanden”(英文:“MyFiles”?)向下滚动有一个条目 "external-sd" ,单击它会打开文件夹 "/sdcard/external_sd/" 。假设我想打开一个文本文件“MyBooks.txt”,我将使用以下内容:

   String Filename = "/mnt/sdcard/external_sd/MyBooks.txt" ;
   File file = new File(fname);...etc...