Doubt about reading txt files on Android?

4

Based on this stackoverflow question in the answer, this code is suggested

try {
    AssetManager assetManager = getResources().getAssets();
    InputStream inputStream = assetManager.open("nome-do-arquivo.txt");
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    String linha;
    LinkedList<String> linhas = new LinkedList<String>();
    while((linha = bufferedReader.readLine())!=null){
        //aqui com o valor da linha vc pode testar o que quiser, por exemplo: linha.equals("123")
        linhas.add(linha);
    }
    inputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

Doubt is with more variables as the command for it to jump jumps and stores the value in the variable within while . and the main doubt which folder should be arquivo txt on Android? , since only the file name is passed.

    
asked by anonymous 21.02.2016 / 21:04

2 answers

3

Come on:

1.

  

Doubt is more variable as the command for it to jump   aligns and stores the value in the variable within the while.

This is done within the while condition:

while((linha = bufferedReader.readLine())!=null)

Note that it adds the variable linha to the value of bufferedReader.readLine() . And this will occur until it is different from null .

More simply:

 String linha ="";
 LinkedList<String> listLinhas = new LinkedList<>(0);
 while(linha !=null){ // enquanto não for null..
     linha = bufferedReader.readLine();   // lemos a próxima linha...
     listLinhas.add(linha); // adicionamos a linha na LinkedList
 }

2.

  

And the main question which folder should be txt file on Android ?,   because only the file name is passed.

In the Assets folder, so we can use AssetManager .

Here's how to create this folder:

In Android Studio, right-click the and navigate to Assets Folder.

Afterconfirmingclickingfinish,thefolderwillbecreated:

    
22.02.2016 / 11:03
4

As the question code is located, the text file must be in the assets folder.

However, according to this answer in SOEn , you can create a folder called raw in the res folder (if it does not already exist) and save the text file there, so it becomes an accessible resource as R.raw.meuArquivoTXT :

String result;
    try {
        Resources res = getResources();
        InputStream in_s = res.openRawResource(R.raw.meuArquivoTXT);

        byte[] b = new byte[in_s.available()];
        in_s.read(b);
        result = new String(b);
    } catch (Exception e) {
        // e.printStackTrace();
        result = "Error: can't show file.";
    }

More information can be found in the documentation:

link

    
21.02.2016 / 21:13