Question about reading txt files on Android?

Asked

Viewed 4,120 times

4

On the basis of that question by stackoverflow in the reply is suggested this code

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

The question is with more variables which command for it to jump aligns and stored the value in the variable inside the while. and the main question which folder should be arquivo txt on Android?, because only the file name is passed.

2 answers

4

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

However, according to this answer in Soen, you can create a folder called raw inside the briefcase res(if it no longer exists) and save the text file there, thus it becomes an accessible resource like 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:

http://developer.android.com/intl/pt-br/tools/projects/index.html

3


Come on:

1.

The doubt is with more variables which command for him to jump align and store the value in the variable inside the while.

This is done within the while:

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

Note that it adds the variable linha the value of bufferedReader.readLine(). And this will happen 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 get txt file on Android? , because only the file name is passed.

In the Assets folder, so we can use the AssetManager.

Here’s how to create this folder:

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

inserir a descrição da imagem aqui

After confirming by clicking on Finish, the folder will be created:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.