J’essaie de lire un simple fichier texte dans mon exemple d’application Android. J’utilise le code écrit ci-dessous pour lire le fichier texte simple.
InputStream inputStream = openFileInput("test.txt"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
Mes questions sont: Où dois-je placer ce fichier "test.txt"
dans mon projet ?. J’ai essayé de mettre le fichier sous le dossier "res/raw"
et "asset"
mais je reçois l’ exception "FileNotFound"
lorsque le premier live du code écrit ci-dessus est exécuté.
Merci pour l’aide
Placez votre fichier texte dans le répertoire /assets
du projet Android. Utilisez la classe AssetManager
pour y accéder.
AssetManager am = context.getAssets(); InputStream is = am.open("test.txt");
Ou vous pouvez également placer le fichier dans le répertoire /res/raw
, où le fichier sera indexé et accessible par un identifiant dans le fichier R:
InputStream is = context.getResources().openRawResource(R.raw.test);
essaye ça,
package example.txtRead; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.SsortingngTokenizer; import java.util.Vector; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class txtRead extends Activity { Ssortingng labels="caption"; Ssortingng text=""; Ssortingng[] s; private Vector wordss; int j=0; private SsortingngTokenizer tokenizer; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wordss = new Vector (); TextView helloTxt = (TextView)findViewById(R.id.hellotxt); helloTxt.setText(readTxt()); } private Ssortingng readTxt(){ InputStream inputStream = getResources().openRawResource(R.raw.toc); // InputStream inputStream = getResources().openRawResource(R.raw.internals); System.out.println(inputStream); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int i; try { i = inputStream.read(); while (i != -1) { byteArrayOutputStream.write(i); i = inputStream.read(); } inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return byteArrayOutputStream.toSsortingng(); } }
Voici comment je le fais:
public static Ssortingng readFromAssets(Context context, Ssortingng filename) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename))); // do reading, usually loop until end of file reading SsortingngBuilder sb = new SsortingngBuilder(); Ssortingng mLine = reader.readLine(); while (mLine != null) { sb.append(mLine); // process line mLine = reader.readLine(); } reader.close(); return sb.toSsortingng(); }
utilisez-le comme suit:
readFromAssets(context,"test.txt")
Avoir un fichier dans votre dossier de assets
vous oblige à utiliser ce morceau de code pour obtenir des fichiers du dossier assets
:
yourContext.getAssets().open("test.txt");
Dans cet exemple, getAssets()
renvoie une instance AssetManager
et vous êtes libre d’utiliser la méthode de votre choix à partir de l’API AssetManager
.
En mono pour Android ….
try { System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt"); ssortingng Content = ssortingng.Empty; using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn)) { try { Content = StrRead.ReadToEnd(); StrRead.Close(); } catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); } } StrIn.Close(); StrIn = null; } catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
Pour lire le fichier enregistré dans le dossier assets
public static Ssortingng readFromFile(Context context, Ssortingng file) { try { InputStream is = context.getAssets().open(file); int size = is.available(); byte buffer[] = new byte[size]; is.read(buffer); is.close(); return new Ssortingng(buffer); } catch (Exception e) { e.printStackTrace(); return "" ; } }
Voici une classe simple qui gère à la fois raw
fichiers raw
et asset
:
classe publique ReadFromFile {
public static Ssortingng raw(Context context, @RawRes int id) { InputStream is = context.getResources().openRawResource(id); int size = 0; try { size = is.available(); } catch (IOException e) { e.printStackTrace(); return ""; } return readFile(size, is); } public static Ssortingng asset(Context context, Ssortingng fileName) { InputStream is = null; int size = 0; try { is = context.getAssets().open(fileName); AssetFileDescriptor fd = null; fd = context.getAssets().openFd(fileName); size = (int) fd.getLength(); fd.close(); } catch (IOException e) { e.printStackTrace(); return ""; } return readFile(size, is); } private static Ssortingng readFile(int size, InputStream is) { try { byte buffer[] = new byte[size]; is.read(buffer); is.close(); return new Ssortingng(buffer); } catch (Exception e) { e.printStackTrace(); return ""; } }
}
Par exemple :
ReadFromFile.raw(context, R.raw.textfile);
Et pour les fichiers d’actifs:
ReadFromFile.asset(context, "file.txt");