I wrote something a couple days ago. I don’t know if i’ll use this method to store values (i guess i’ll use xml). Anyway, the point is getting a value from a variable in the String type, and then convert it to integer or another type. The method read and search in the txt file for the “<”+“variable name” + “=”, so i named this string as “beforeValue”, and another String called “afterValue” (just what i have after the value, including the variable to identify the block, in this case the “;”+variable+">").
I have to wrote something like this in my txt file: <x=10;x> The method will return the “10” in String, and then i convert it to integer.
Code:
//Data class constructor
public Data() {
int x = Integer.parseInt(readValue("C:/myTxt.txt", "x")); //txt path and the variable you're looking for the value.
System.out.println("The variable value is "+ x); //write 10;
}
//Read method
public String readValue(String txtPath, String variable) {
String value = "0", contents = "", beforeValue = "<" + variable + "=", afterValue = ";" + variable + ">";
boolean found = false;
try {
BufferedReader read = new BufferedReader(new FileReader(txtPath));
while((contents = read.readLine()) != null && !found){
if (contents.contains(beforeValue)) {
value = contents.substring(contents.indexOf(beforeValue) + beforeValue.length(), contents.indexOf(afterValue));
found = true;
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return value;
}
Obs: The txt file content also works in sequence:
E.g1 (same line): <x=10;x> <y=30;y> <z=50;z>
E.g2 (line breaking): <x=10;x>
<y=30;y>
<z=50;z>