Friday, 24 June 2016

java - How to convert InputStream to int




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

Answer




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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...