如何在安卓系统中读取文本文件?

2022-08-31 08:19:28

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

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

答案 1

试试这个 :

我假设您的文本文件在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());

以下链接也可以帮助你:

如何在安卓系统中读取SD卡中的文本文件?

如何在安卓系统中读取文本文件?

安卓读取文本原始资源文件


答案 2

如果你想从SD卡读取文件。然后,以下代码可能对您有所帮助。

 StringBuilder text = new StringBuilder();
    try {
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,"testFile.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));  
        String line;   
        while ((line = br.readLine()) != null) {
                    text.append(line);
                    Log.i("Test", "text : "+text+" : end");
                    text.append('\n');
                    } }
    catch (IOException e) {
        e.printStackTrace();                    

    }
    finally{
            br.close();
    }       
    TextView tv = (TextView)findViewById(R.id.amount);  

    tv.setText(text.toString()); ////Set the text to text view.
  }

    }

如果您想从资产文件夹中读取文件,那么

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

或者,如果您想要从 foldery 读取此文件,该文件将被编入索引,并且可通过 R 文件中的 id 访问:res/raw

InputStream is = getResources().openRawResource(R.raw.test);     

从 res/raw 文件夹中读取文本文件的良好示例