【问题标题】:How can I read a text file from the SD card in Android?如何从 Android 的 SD 卡中读取文本文件?
【发布时间】:2011-02-23 13:35:22
【问题描述】:

我是 Android 开发新手。

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

【问题讨论】:

  • 您想知道如何编写一个读取 txt 文件的程序,还是想知道如何以用户身份进行操作?

标签: android android-sdcard


【解决方案1】:

In your layout 你需要一些东西来显示文本。 TextView 是显而易见的选择。所以你会有这样的东西:

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

您的代码将如下所示:

//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);

这可以在你的Activity 的onCreate() 方法中使用,或者在其他地方,这取决于你想要做什么。

【讨论】:

  • @Android Developer - 在示例代码中它说“您需要在此处添加适当的错误处理”。您这样做是因为这可能是您最容易发现问题的地方。
  • @Dave Webb 很抱歉没有更新我的评论。它也适用于我。实际上,当我将文件放入 DDMS 时,它会清除文件中的所有数据,这就是为什么它在我最后返回 null 的原因。
  • 这可以使用共享网络文件吗?我想在互联网上的共享文件中归档一个文件,文件目录看起来像“192.168.197.84/hdd1”、“ActivityLog.txt”
  • 非常感谢 Dave,能否请您演示如何将 wave/mp3 文件以及读取到字节数组中。
  • @DaveWebb:您还应该在清单文件中添加使用权限:READ_EXTERNAL_STORAGE
【解决方案2】:

回应

不要硬编码 /sdcard/

有时我们必须对其进行硬编码,因为在某些手机型号中,API 方法会返回手机内部存储器。

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

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

【讨论】:

  • 对我来说,它提供了一些安全性垃圾/com.app.name/data/sdcard/ ...请注意。对于我自己的日志,我最后对其进行了硬编码。
【解决方案3】:

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

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

从 android 6.0 或更高版本开始,您的应用必须在运行时要求用户授予危险权限。请参考这个链接 Permissions overview

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);
    }
}

【讨论】:

  • 权限是6.0以上的线索。谢谢!
【解决方案4】:
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();
                    }
                }
            }

        }
    }
}

【讨论】:

    【解决方案5】:
    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 
            }
    

    【讨论】:

    • 你能解释一下你的代码吗..比如在哪里使用它,为什么这样做,等等。
    【解决方案6】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-03
      • 2011-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多