voldy
voldy

Reputation: 387

different output for FileReader and FileInputStream

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
public class Main {
    public static void main(String[] args) throws IOException {
        FileReader fileReader1 = new FileReader("C:\\test\\input.txt");
        FileInputStream fileInputStream1 = new FileInputStream("C:\\test\\input.txt");
        FileReader fileReader2 = new FileReader("C:\\test\\abc.png");
        FileInputStream fileInputStream2 = new FileInputStream("C:\\test\\abc.png");

        int ab=fileReader1.read(); 
        int bc=fileInputStream1.read();

        int ab1=fileReader2.read();
        int bc1=fileInputStream2.read();

        System.out.println("reading a file : fileReader:"+ab+" fileInputStream:"+bc);
        System.out.println("resding  PNG : fileReader:"+ab1+" fileInputStream:"+bc1);
    }
}

Output:

reading a file : fileReader:104 fileInputStream:104
resding  PNG : fileReader:8240 fileInputStream:137

i am using FileReader and FileInputStream for reading a txt file and reading an image file. i know on reads byte wise and other char wise. but im not getting this ouptput.

Upvotes: 2

Views: 675

Answers (2)

bithead61
bithead61

Reputation: 196

The first byte in a PNG file is 0x89, or 137 decimal. FileInputStream reports the byte as is, while FileReader assumes that it is a character in the Windows 1252 code page and converts it to the corresponding UTF-8 character code, 0x2030, or 8240 decimal. (This assumes you ran the code on a Windows machine with default code page 1252).

Upvotes: 1

Stijn Geukens
Stijn Geukens

Reputation: 15628

FileReader:

Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.

FileInputStream:

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

Upvotes: 1

Related Questions