Duarte Arribas
Duarte Arribas

Reputation: 317

Reading from binary file with FileInputStream returning 0

I have the following code:

File file=new File("src/com/yoznacks/main/stuff.txt");
FileInputStream foo=new FileInputStream(file);
int a;
while((a=foo.read())!=-1){
    System.out.print((char)a);
}

My file is as follows:

aaaaa

But the output is

a a a a a

Why is that?

Upvotes: 0

Views: 108

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109557

You are reading bytes. If the file's text were encoded in UTF-16LE then the bytes would be 0x61 0x00 0x61 0x00 0x61 0x00 0x61 0x00 0x61 0x00, where 0x61 as char is 'a'.

For reading text instead of bytes java uses *Reader instead of *InputStream, together with specifying the encoding (Charset) of the bytes.

try (InputStream in = getClass().getResourceAsStream("/com/yoznacks/main/stuff.txt");
        InputStreamReader foo = new InputStreamReader(in, StandardCharsets.UTF_16LE)) {
    int a;
    while ((a = foo.read()) !=-1 ) {
        System.out.print((char)a);
    }
    System.out.println(); // Output, flush all.
} // foo and in are closed.

InputStreamReader takes a binary InputStream and given a Charset of the bytes produces Unicode text, char.

If the file is part of the application (like zipped in the application jar), then it is a resource, and can be read with getResource(AsStream).

Upvotes: 1

Related Questions