Comment puis-je lire un fichier texte sur Android?

je veux lire le texte d'un fichier texte. Dans le code ci-dessous, une exception se produit (cela signifie qu'il va au bloc catch ). J'ai mis le fichier texte dans le dossier de l'application. Où dois-je mettre ce fichier texte (mani.txt) afin de lire correctement?

    try
    {
        InputStream instream = openFileInput("E:testsrccomtestmani.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();
    }
87
demandé sur Jamal 2012-09-14 13:35:10

7 réponses

essayez ceci:

je suppose que votre fichier texte est sur la carte 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());

les liens suivants peuvent aussi vous aider:

Comment puis-je lire un fichier texte à partir de la carte SD sur Android?

Comment lire un fichier texte sous Android?

Android lire le texte raw fichier de ressources

187
répondu Shruti 2018-01-28 02:07:44

si vous voulez lire le fichier de la carte sd. Alors suivre le code pourrait être utile pour vous.

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

    }

si vous voulez lire le fichier du dossier d'actif alors

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

ou si vous voulez lire ce fichier de res/raw foldery, où le fichier sera indexé et est accessible par un id dans le fichier R:

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

Bon exemple de lecture de fichier texte à partir res/raw dossier

24
répondu Sandip Armal Patil 2015-01-22 10:55:14

Placez votre fichier texte dans le dossier Asset ... et lire le fichier dans ce dossier...

voir les liens de référence ci-dessous...

http://www.technotalkative.com/android-read-file-from-assets/

http://sree.cc/google/reading-text-file-from-assets-folder-in-android

lecture d'un simple fichier texte

j'espère que ça aidera...

6
répondu Priyank Patel 2017-05-23 12:26:17

vous stockez D'abord votre fichier texte dans le dossier raw.

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.");
}
2
répondu Ram 2016-11-29 16:15:08

Essayez cette

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
répondu Muhammad Usman Ghani 2014-02-27 07:48:19

essayez ce 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
répondu HuynhHan 2016-11-29 16:50:25
// working
public static String getStringFromFile (String filename) throws Exception {


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

    FileInputStream fin = new FileInputStream(file);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();        
    return ret;
}
-4
répondu Khan 2014-07-20 04:45:06