fkchaud
fkchaud

Reputation: 345

How do I get certain values from a txt file?

I'm kind of noob in Android and I need help with something. I have a .txt file like this:

#nombre iron will#

#fuerza 6#
#const 6#
#habilidad 6#
#intelig 6#

#vitalidad 42#
#aguante 72#

What I want to do is to get every item in the .txt file and store it in a variable. For example, in this case I want a String variable called "nombre" with the value "Will", an int variable "fuerza" with the value "6", etc.

How can I get this? Thanks in advance, and sorry about my bad english.

My code so far:

File tarjeta = Environment.getExternalStorageDirectory();
File carpeta = new File(tarjeta.getAbsolutePath() + "/Rol/PJs/");
File archivo = new File(carpeta.getAbsolutePath(), archivoabierto); //String archivoabierto = "name.txt"
StringBuilder text = new StringBuilder();
try{
     //This is where I get lost, I don't know how to proceed
     BufferedReader br = new BufferedReader(new FileReader(archivo));
     String line;
     while ((line = br.readLine()) != null){
           text.append(line);
           text.append('\n');
     }
     br.close();
} catch (IOException e){
     Toast.makeText(Personajes.this, "No se pudo cargar "+archivo.getPath(), Toast.LENGTH_SHORT).show();
}

EDIT: I'm using json format now and it works. Thanks all!

Upvotes: 1

Views: 64

Answers (2)

arash javanmard
arash javanmard

Reputation: 1387

you could also use

String[] parts = text.split(" ");
String key = parts[0];
String value = parts[1];

but i recommand to use json-format.

Upvotes: 1

mariopce
mariopce

Reputation: 1136

Please use SharedPreferences to store key-values, It is much easier. http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/

Upvotes: 0

Related Questions