I use a BufferedReader to read lines from an InputStream. When I read something directly from the InputStream, the BufferedReader ignores my read and continues reading at the same location. Is it possible to prevent this behavior? If not what is a good practice to do this?
PS: Here's my code:
byte[] ba = new byte[1024*1024];
int off = 0;
int len = 0;
do {
len = Integer.parseInt(br.readLine());
in.read(ba, off, len);
br.readLine();
off += len;
} while(len > 0);
in
is my inputstream and br
my bufferedreader.
If not what is a good practice to do this?
This is not a good approach to read by 2 stream at a time for same file. You have to use just one stream.
BufferedReader
is used for character
stream whereas InputStream
is used for binary
stream.
A binary stream doesn't have readLine()
method that is only available in character
stream.
Reading from a BufferedReader and an InputStream at the same time is not possible. If you need binary data, you should use multiple readLine() calls.
Here's my new code:
byte[] ba = new byte[1024*1024];
int off = 0;
int len = 0;
do {
len = Integer.parseInt(br.readLine().split(";" , 2)[0],16);
for (int cur = 0; cur < len;) {
byte[] line0 = br.readLine().getBytes();
for (int i = 0; i < line0.length; i++) {
ba[off+cur+i] = line0[i];
}
cur += line0.length;
if(cur < len) {
ba[off+cur] = '\n';
cur++;
}
}
off += len;
} while(len > 0);
BufferedReader bufferedReader = null;
try
{
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = bufferedReader.readLine()) != null)
{
//process lines here
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch(IOException e)
{
}
}
}