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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.