Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert InputStream to int [duplicate]

Tags:

java

string

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);
like image 489
xflea Avatar asked Jan 03 '15 21:01

xflea


People also ask

Can I read InputStream twice?

Don't read it twice. Save the result in a data structure.

How do I change InputStream to string?

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.

Why does InputStream read return an int?

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.


2 Answers

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();     
}
like image 172
karlphillip Avatar answered Oct 21 '22 04:10

karlphillip


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());
}
like image 34
Piotr Praszmo Avatar answered Oct 21 '22 04:10

Piotr Praszmo