Comment lire un fichier texte sous Android?


117

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

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

4
qu'espérez-vous que votre émulateur fasse partie de votre s / m? "E: \\ test \\ src \\ com \\ test \\ mani.txt"
— Athul Harikumar

2
à partir de quel emplacement vous souhaitez lire le fichier texte ...?
— Sandip Armal Patil le

2
InputStream iS = resources.getAssets (). Open (fileName); (si vous mettez le fichier dans les actifs)
— Athul Harikumar

1
@Sandip en fait, j'ai copié le fichier texte (mani.txt) et l'ai mis dans le dossier de l'application Android (dossier ayant .settings, bin, libs, src, assets, gen, res, androidmanifeast.xml)
— user1635224

2
ou mettez simplement dans le dossier res / raw et vérifiez ma réponse mise à jour.
— Sandip Armal Patil le

Réponses:


244

Essaye ça :

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 également vous aider:

Comment puis-je lire un fichier texte depuis la carte SD sous Android?

Comment lire un fichier texte sous Android?

Fichier de ressources brutes de lecture de texte Android


3
votre lien serait m'aide à atteindre
— user1635224

10
Le BufferedReader doit se fermer à la fin!
— RainClick

2
Si vous avez une ligne vide dans votre doc txt, cet analyseur cessera de fonctionner! La solution est d'admettre avoir ces lignes vides: while ((line = br.readLine()) != null) { if(line.length() > 0) { //do your stuff } }
— Choletski

@Shruti comment ajouter le fichier sur la carte SD
— Tharindu Dhanushka

@Choletski, pourquoi dites-vous que cela cessera de fonctionner? S'il y a une ligne vide, la ligne vide sera ajoutée au texte StringBuilder. Quel est le problème?
— LarsH

29

Si vous souhaitez lire le fichier de la carte SD. Ensuite, le code suivant pourrait vous être utile.

 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 souhaitez lire le fichier à partir du dossier d'actifs,

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

Ou si vous souhaitez lire ce fichier à partir de res/rawfoldery, où le fichier sera indexé et est accessible par un identifiant dans le fichier R:

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

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


2
brest hors de portée dans le bloc finally.
— AlgoRythm


3

Tout d'abord, vous stockez votre fichier texte dans un dossier brut.

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.");
}

3

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

1

Essaye ça

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);
  }
En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.