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

发布于 2024-09-03 00:45:30 字数 97 浏览 9 评论 0原文

我是 Android 开发新手。

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

I am new to Android development.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

帅气称霸 2024-09-10 00:45:30

在你的布局中你需要一些东西显示文本。 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);

这可以放在 ActivityonCreate() 方法中,或者其他地方,具体取决于你想做什么。

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

<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.

无声静候 2024-09-10 00:45:30

回应

不要硬编码/sdcard/

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

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

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

In response to

Don't hardcode /sdcard/

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

Known types: HTC One X and Samsung S3.

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

反差帅 2024-09-10 00:45:30

您应该具有 READ_EXTERNAL_STORAGE 权限才能读取 SD 卡。
在manifest.xml中添加权限

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

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

You should have READ_EXTERNAL_STORAGE permission for reading sdcard.
Add permission in 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

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);
    }
}
鹊巢 2024-09-10 00:45:30
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();
                    }
                }
            }

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

        }
    }
}
浅笑依然 2024-09-10 00:45:30
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 
        }
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 
        }
尬尬 2024-09-10 00:45:30

请注意:有些手机有 2 张 SD 卡,一张内置固定卡和一张可移动卡。
您可以通过标准应用程序找到最后一个的名称:“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...

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 :

   String Filename = "/mnt/sdcard/external_sd/MyBooks.txt" ;
   File file = new File(fname);...etc...
临风闻羌笛 2024-09-10 00:45:30

不幸的是,所有这些答案都是无用的,因为自 Android 11 (API 30) 以来就已经过时了。由于 Google 政策(我不明白),从那时起,对内部或 SD 卡的文件访问受到严格限制,这种方式并不真正明智:

  1. 您可以使用 SAF 机制来打开目录或单个文件。请注意,SAF 是 Google 专有的,甚至某些 Android 部件(例如 SQL)也不支持,而且它非常慢,大​​约为 1/20 到 1/100。这也适用于 Android 7 等。
  2. 您可以请求 MANAGE_EXTERNAL_STORAGE 权限。这适用于 Android 11 及更高版本,但您将无法在 Play 商店中发布您的程序,除非您假装它是文件管理器。
  3. 如果您的程序请求 READ_EXTERNAL_STORAGE 或其 Android 13 (API 33) 挂件 READ_MEDIA_*,您将无法也永远无法访问文本或数据库文件,只能访问音频、电影或图像。无论出于何种原因。因此,请勿尝试或将其用作 Android 版本 10 之前的后备。

All of these answers are unfortunately useless, because outdated since Android 11 (API 30). Due to Google policy, that I do not appreciate, file access to internal or SD card is since then strictly limited in a way that is not really sensible:

  1. You may use SAF mechanism to open directories or single files. Note that SAF is Google proprietary, not supported even by some Android parts, e.g. SQL, and it is extremely slow, about factor 1/20 down to 1/100. This will also work with Android 7 etc..
  2. You may request for MANAGE_EXTERNAL_STORAGE permission. This works with Android 11 and newer, but you will not be allowed to publish your program in Play Store, unless you pretend it's a file manager.
  3. If your program requests READ_EXTERNAL_STORAGE or its Android 13 (API 33) pendants READ_MEDIA_*, you will not and never be able to access text or database files, only audio, movies or images. For whatever reason. So do not try it or use it as fallback for Android versions up to 10.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文