How can I read a text file in Android?

前端 未结 7 1393
-上瘾入骨i
-上瘾入骨i 2020-11-22 07:51

I want to read the text from a text file. In the code below, an exception occurs (that means it goes to the catch block). I put the text file in the applicati

相关标签:
7条回答
  • 2020-11-22 08:36

    Try this

    try {
            reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
          String line="";
          String s ="";
       try 
       {
           line = reader.readLine();
       } 
       catch (IOException e) 
       {
           e.printStackTrace();
       }
          while (line != null) 
          {
           s = s + line;
           s =s+"\n";
           try 
           {
               line = reader.readLine();
           } 
           catch (IOException e) 
           {
               e.printStackTrace();
           }
        }
        tv.setText(""+s);
      }
    
    0 讨论(0)
  • 2020-11-22 08:42

    First you store your text file in to raw folder.

    private void loadWords() throws IOException {
        Log.d(TAG, "Loading words...");
        final Resources resources = mHelperContext.getResources();
        InputStream inputStream = resources.openRawResource(R.raw.definitions);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strings = TextUtils.split(line, "-");
                if (strings.length < 2)
                    continue;
                long id = addWord(strings[0].trim(), strings[1].trim());
                if (id < 0) {
                    Log.e(TAG, "unable to add word: " + strings[0].trim());
                }
            }
        } finally {
            reader.close();
        }
        Log.d(TAG, "DONE loading words.");
    }
    
    0 讨论(0)
  • 2020-11-22 08:43

    Try this :

    I assume your text file is on sd card

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

    following links can also help you :

    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

    0 讨论(0)
  • 2020-11-22 08:46

    If you want to read file from sd card. Then following code might be helpful for you.

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

    If you wan to read file from asset folder then

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

    Or If you wan to read this file from res/raw foldery, where the file will be indexed and is accessible by an id in the R file:

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

    Good example of reading text file from res/raw folder

    0 讨论(0)
  • 2020-11-22 08:49

    Shortest form for small text files (in Kotlin):

    val reader = FileReader(path)
    val txt = reader.readText()
    reader.close()
    
    0 讨论(0)
  • 2020-11-22 08:51

    Try this code

    public static String pathRoot = "/sdcard/system/temp/";
    public static String readFromFile(Context contect, String nameFile) {
        String aBuffer = "";
        try {
            File myFile = new File(pathRoot + nameFile);
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
            String aDataRow = "";
            while ((aDataRow = myReader.readLine()) != null) {
                aBuffer += aDataRow;
            }
            myReader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return aBuffer;
    }
    
    0 讨论(0)
提交回复
热议问题