How to convert InputStream to int
10,011
Solution 1
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();
}
Solution 2
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());
}
Author by
xflea
Updated on July 20, 2022Comments
-
xflea almost 2 years
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);
-
xflea over 9 yearsThe method getStringFromInputStream() cannot be resolved, so i tried this: String valore1 = getResources().getResourceEntryName(R.raw.max_easy); int num = Integer.parseInt(valore1); EasyTxt.setText(num); // the line will be displayed in this textview but as soon as the activity starts the app stop working, anyway Android Studio is giving me no errors... why? :(
-
karlphillip over 9 yearsUpdated answer, sorry.
-
xflea over 9 yearsGreat, now the app is working fine! Thank you for the help!