NamHo Lee
NamHo Lee

Reputation: 329

Using InputStream and InputStreamReader at the same time in java

I made an InputStream Object from a file and a InputStreamReader from that.

InputStream ips = new FileInputStream("c:\\data\\input.txt");
InputStreamReader isr = new InputStreamReader(ips);

I will basically read data in the form of bytes to a buffer but when there comes a time when i should read in chars I will 'switch mode' and read with InputStreamReader

byte[] bbuffer = new byte[20];
char[] cbuffer = new char[20];

while(ips.read(buffer, 0, 20)!=-1){
    doSomethingWithbBuffer(bbuffer);
    // check every 20th byte and if it is 0 start reading as char
    if(bbuffer[20] == 0){  
        while(isr.read(cbuffer, 0, 20)!=-1){
            doSomethingWithcBuffer(cbuffer);
            // check every 20th char if its # return to reading as byte
            if(cbuffer[20] == '#'){
                break;
            }
        }
    } 
}

is this a safe way to read files that have mixed char and byte data?

Upvotes: 1

Views: 596

Answers (1)

jtahlborn
jtahlborn

Reputation: 53674

no, this is not safe. the InputStreamReader may read "too much" data from the underlying stream (it uses internal buffers) and corrupt your attempt to read from the underlying byte stream. You can use something like DataInputStream if you want to mix reading characters and bytes.

Alternately, just read the data as bytes and use the correct character encoding to convert those bytes to characters/Strings.

Upvotes: 2

Related Questions