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

标签 java android exception inputstream

我想从文本文件中读取文本。在下面的代码中,发生了一个异常(这意味着它进入了 catch block )。我将文本文件放在应用程序文件夹中。我应该把这个文本文件(mani.txt)放在哪里才能正确阅读?

    try
    {
        InputStream instream = openFileInput("E:\\test\\src\\com\\test\\mani.txt"); 
        if (instream != null)
        {
            InputStreamReader inputreader = new InputStreamReader(instream); 
            BufferedReader buffreader = new BufferedReader(inputreader); 
            String line,line1 = "";
            try
            {
                while ((line = buffreader.readLine()) != null)
                    line1+=line;
            }catch (Exception e) 
            {
                e.printStackTrace();
            }
         }
    }
    catch (Exception e) 
    {
        String error="";
        error=e.getMessage();
    }

最佳答案

试试这个:

我假设你的文本文件在 sd 卡上

    //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.toString());

以下链接也可以帮助您:

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

How to read text file in Android?

Android read text raw resource file

关于java - 如何在 Android 中读取文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12421814/

相关文章:

Java 鼠标事件未在 OSX 上注册

java - 抽象类混淆,对象声明和对象引用?

java - Apache Camel 到 SOAP API 的路由

java - 无法获取 api key 的 md5 指纹

java - 如何捕获 401,403 错误并响应成功 200

java - 如何将数据从 DialogFragment 发送到 Fragment?

android - 如何跟踪 Amazon SNS 发送的打开的推送通知

c# - CSharpProvider 运行时编译找不到 DLL

python - 基于特定数据框列处理异常

java - StringBuffer 数组在 String 工作的地方失败