I have a txt file called "max_easy.txt" in /raw folder, in this file is written a number, in this case in "0"... I want a var which have 0 as a Int value, how do i do that?
I guess this line gives me a String value, how do i convert it?
InputStream letturaEasy = getResources().openRawResource(R.raw.max_easy);
Don't read it twice. Save the result in a data structure.
To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.
It returns an int because when the stream can no longer be read, it returns -1. If it returned a byte, then -1 could not be returned to indicate a lack of input because -1 is a valid byte. In addition, you could not return value above 127 or below -128 because Java only handles signed bytes.
If this is what you got so far:
InputStream letturaEasy = getResources().openRawResource(R.raw.max_easy);
Then all that needs to be done is to convert that to a String:
String result = getStringFromInputStream(letturaEasy);
And finally, to int:
int num = Integer.parseInt(result);
By the way, getStringFromInputStream()
was implemented here:
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
You can use BufferedReader
to read lines as strings from that file. Integer.parseInt
will parse them to ints:
try(BufferedReader reader = new BufferedReader(new InputStreamReader(letturaEasy, "UTF8")) ) {
int n = Integer.parseInt(reader.readLine());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With