Question

Good evening!

I have been reading through stuff on the internet for hours now but I can't find any way to get the conent of a file from the internet into an int array.

I got a .txt file (that I download from the internet) which is loaded over a BufferedStreamInput. There is a byte array which I tried to make use of it, but didn't have much success. Inside the file are random letters such as "abcCC". Now I would need the int value of each character (such as 97,98,99,67,67). I would add them to an array and then count how often a specific value appears. My problem tho is to get those values from the stream and I don't seem to find a way to do so.

Thank you for any ideas!

Was it helpful?

Solution

The Java API already contains a method that seems very convenient for you. InputStream defines the following method.

public abstract int read() throws IOException;

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

It should make it trivial to read integers from a file one byte at a time (assuming characters to integers is one-to-one; int is actually four bytes in size).


An example of using this method to read characters individually as int and then casting to char follows. Again, this assumes that each character is encoded as a single byte, and that there is a one-to-one from characters to ints. If you're dealing with multi-byte character encoding and/or you want to support integers greater than 255, then the problem becomes more complex.

public static void main(String[] args) {
    ByteArrayInputStream in = new ByteArrayInputStream("abc".getBytes());
    int value;
    while ((value = in.read()) > -1) {
        System.out.println((char) value);
    }
}

OTHER TIPS

I would use a

java.util.Scanner.

You can initialize it with many different options including

File 
InputStream
Readable

Later you can process the whole input line by line or in any way you like. please refer to the great javadoc of Scanner.

Regards,

z1pi

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top