473,394 Members | 1,802 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Buffered Reader

73
I am using buffered Reader.....some problem arises ...dnt know why....am using the following code to read a big file about 8MB.

path = "/home/t.txt"

File file=new File(path);
FileReader freader=new FileReader(file);
BufferedReader reader=new BufferedReader(freader);

System.out.println(reader.ready());
while((line = reader.readLine()) != null)
{
//some code
}

in the above case it sometimes gives reader.ready() is false....and so it does not enter the while loop wat could be the fix....and why its giving reader.ready() is false
reason and wat is the fix for it...
Aug 10 '07 #1
15 2142
JosAH
11,448 Expert 8TB
I am using buffered Reader.....some problem arises ...dnt know why....am using the following code to read a big file about 8MB.

path = "/home/t.txt"

File file=new File(path);
FileReader freader=new FileReader(file);
BufferedReader reader=new BufferedReader(freader);

System.out.println(reader.ready());
while((line = reader.readLine()) != null)
{
//some code
}

in the above case it sometimes gives reader.ready() is false....and so it does not enter the while loop wat could be the fix....and why its giving reader.ready() is false
reason and wat is the fix for it...
No matter the value of ready(), your code enters that while loop as far as I can see.
Did you show us the code you were running?

I ripped the following straight from the API docs for the BufferedReader class:

Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.
When the reader is freshly opened, it may not have filled its buffer yet; that could
be a reason for ready() to return false. Don't pay any attention to it and just
read away.

kind regards,

Jos
Aug 10 '07 #2
jyohere
73
No matter the value of ready(), your code enters that while loop as far as I can see.
Did you show us the code you were running?

I ripped the following straight from the API docs for the BufferedReader class:



When the reader is freshly opened, it may not have filled its buffer yet; that could
be a reason for ready() to return false. Don't pay any attention to it and just
read away.

kind regards,

Jos

This is the same code am using.....i printed reader.ready() only after it was not entering the loop... i am using it in my project now....i got the error when it was
tested for stress test....it was working fine when the file size was small...
Aug 10 '07 #3
jyohere
73
This is the same code am using.....i printed reader.ready() only after it was not entering the loop... i am using it in my project now....i got the error when it was
tested for stress test....it was working fine when the file size was small...

The code i said above is in a function....it will get called and then the while loop has to execute immediately the first time itself....
Aug 10 '07 #4
JosAH
11,448 Expert 8TB
This is the same code am using.....i printed reader.ready() only after it was not entering the loop... i am using it in my project now....i got the error when it was
tested for stress test....it was working fine when the file size was small...
I'm afraid the error is somewhere else then; check if the file exists; if so read it
and see if the while loop *terminates* properly. Maybe an unchecked exception
what thrown somewhere in the body of that while loop.

If you wrap a BufferedReader around a FileReader, the ready() method doesn't
tell you much.

kind regards,

Jos
Aug 10 '07 #5
jyohere
73
I'm afraid the error is somewhere else then; check if the file exists; if so read it
and see if the while loop *terminates* properly. Maybe an unchecked exception
what thrown somewhere in the body of that while loop.

If you wrap a BufferedReader around a FileReader, the ready() method doesn't
tell you much.

kind regards,

Jos
then why is it not entering the loop only when reader.ready() is false?
Aug 10 '07 #6
JosAH
11,448 Expert 8TB
then why is it not entering the loop only when reader.ready() is false?
I don't know because you didn't show us any relevant code that showed the
symptoms you keep on mentioning.

kind regards,

Jos
Aug 10 '07 #7
jyohere
73
I don't know because you didn't show us any relevant code that showed the
symptoms you keep on mentioning.

kind regards,

Jos
this is the method.....sry its too big Jos

public static ArrayList get(int ne_id,int ne_type,

int shelf_id, int card_id, int port_id,

int index1_id, int index2_id,

int index3_id,int index4_id, int[] location,

NameAndStringValue_T[] name,String[] granularity,

String[] pmLocation, short[] layerRate,

String startTime, String endTime){



String[] pmParameters={"PMP_BBE", "PMP_SES", "PMP_ES", "PMP_UAS"};

int index=0;

logger.info("Inside get()");



BufferedReader reader=null;

String line=" ";

ArrayList keyList=new ArrayList();

ArrayList valueList=new ArrayList();

String str[]=null;

String syearStr=" ", eyearStr=" ";

String smonthStr=" ", emonthStr=" ";

String sdateStr=" ", edateStr=" ";

int startDate=0, endDate=0;

StringBuffer fileName=new StringBuffer();

StringBuffer endfileName=new StringBuffer();

String path=" ";

Calendar start_cal,end_cal;

int start_week_of_year=0,end_week_of_year=0;

boolean near=false;



SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");



String sTime=startTime.substring(0,14);

String eTime=endTime.substring(0,14);



ParsePosition p1=new ParsePosition(0);

Date start=dateFormat.parse(sTime,p1);

ParsePosition p2=new ParsePosition(0);

Date end=dateFormat.parse(eTime,p2);



logger.info(HDR + " START TIME : " + start);

logger.info(HDR + " END TIME : " + end);

try{

Matcher m;

if(granularity[0].equalsIgnoreCase("15min")){

syearStr=startTime.substring(0,4);



fileName.append(syearStr);

fileName.append("_");

smonthStr=startTime.substring(4,6);

fileName.append(smonthStr);

fileName.append("_");

sdateStr=startTime.substring(6,8);

fileName.append(sdateStr);

fileName.append("_");

fileName.append("15M");

fileName.append("_");

if(ne_type<=9){

fileName.append("0");

fileName.append(ne_type);

}else{

fileName.append(ne_type);

}

fileName.append(".ppm");



eyearStr=endTime.substring(0,4);

emonthStr=endTime.substring(4,6);

edateStr=endTime.substring(6,8);



startDate=Integer.parseInt(sdateStr);

endDate=Integer.parseInt(edateStr);



}else if(granularity[0].equalsIgnoreCase("24H")){



syearStr=startTime.substring(0,4);

int start_year=Integer.parseInt(syearStr);



fileName.append(syearStr);

fileName.append("_");



smonthStr=startTime.substring(4,6);

int start_month=Integer.parseInt(smonthStr)-1;

sdateStr=startTime.substring(6,8);

int start_date=Integer.parseInt(sdateStr);



start_cal=new GregorianCalendar(start_year,start_month,start_dat e);

start_cal.setMinimalDaysInFirstWeek(7);

start_cal.setFirstDayOfWeek(Calendar.MONDAY);



if ((start_cal.get(Calendar.MONTH) == Calendar.JANUARY) && (start_cal.get(Calendar.WEEK_OF_YEAR) >= 52))

start_week_of_year=0;

else

start_week_of_year=start_cal.get(Calendar.WEEK_OF_ YEAR);



logger.info(HDR+"start_week_of_year " +start_week_of_year);



if(start_week_of_year <=9){

fileName.append("0");

fileName.append(start_week_of_year);

}else{

fileName.append(start_week_of_year);

}

fileName.append("_");

fileName.append("24H");

fileName.append("_");

if(ne_type<=9){

fileName.append("0");

fileName.append(ne_type);

}else{

fileName.append(ne_type);

}

fileName.append(".ppm");



eyearStr=endTime.substring(0,4);

int end_year=Integer.parseInt(eyearStr);



emonthStr=endTime.substring(4,6);

int end_month=Integer.parseInt(emonthStr)-1;

edateStr=endTime.substring(6,8);

int end_date=Integer.parseInt(edateStr);



end_cal=new GregorianCalendar(end_year,end_month,end_date);

end_cal.setMinimalDaysInFirstWeek(7);

end_cal.setFirstDayOfWeek(Calendar.MONDAY);



if ((end_cal.get(Calendar.MONTH) == Calendar.JANUARY) && (end_cal.get(Calendar.WEEK_OF_YEAR) >= 52))

end_week_of_year=0;

else

end_week_of_year=end_cal.get(Calendar.WEEK_OF_YEAR );



logger.info(HDR+"end_week_of_year " +end_week_of_year);



}







path = "/var/ftp/PMFiles/marconi/" + fileName;



logger.info(HDR+"path"+path);



File file=new File(path);

reader=new BufferedReader(new FileReader(file));

logger.info(HDR+"Before while loop");

while((line = reader.readLine()) != null)

{



logger.info(HDR+"Inside while loop");

String[] testStr=line.split(REGEX1);



try{

int test=Integer.parseInt(testStr[testStr.length-1]);

}catch(Exception e){





String newLine= reader.readLine();

StringBuffer buffer=new StringBuffer(line);

buffer.append(newLine);

line=buffer.toString();



}



m=pattern.matcher(line);



boolean matchFound = m.find();

if (matchFound){

str=new String[m.groupCount()+1];



for (int i=0; i<=m.groupCount(); i++)

str[i]=m.group(i);

}



int neId=Integer.parseInt(str[2]);

//logger.info(HDR+"neId " +neId);

int neType=Integer.parseInt(str[3]);

//logger.info(HDR+"neType " +neType);

int shelfId=Integer.parseInt(str[4]);

int cardId=Integer.parseInt(str[6]);

int portId=Integer.parseInt(str[9]);

//logger.info(HDR+"ptp" + shelfId+ " " +cardId +" "+ portId);

int indexId1=Integer.parseInt(str[10]);

int indexId2=Integer.parseInt(str[11]);

int indexId3=Integer.parseInt(str[12]);

int indexId4=Integer.parseInt(str[13]);

//logger.info(HDR+"ctp" + indexId1+ " " +indexId2 +" "+ indexId3+" "+indexId4);

int entityType=Integer.parseInt(str[14]);

//logger.info(HDR+"entity " +entityType);



ParsePosition p=new ParsePosition(0);

Date time=dateFormat.parse(str[18],p);

//logger.info(HDR+"time " +time);



if(((entityType==location[0]||entityType==location[1]))

&& (time.after(start) ||time.equals(start))

&&(time.before(end) ||time.equals(end))

&& neId==ne_id && neType==ne_type && shelfId==shelf_id

&& indexId1==index1_id && indexId2==index2_id && indexId3==index3_id && indexId4==index4_id

&& cardId==card_id && portId ==port_id){





logger.info("Matched so inside data collection...");

StringBuffer key=new StringBuffer();



for(int l=1;l<13;l++){



key.append(str[l]);

key.append(":");

}



key.append(str[18]);

key.append(".0");

String keyStr=key.toString();



StringBuffer value=new StringBuffer();



for(int k=0;k<4;k++){

value.append(name[k].value);

value.append(",");

}



value.append(granularity[0]);

value.append(",");



value.append(layerRate[0]);

value.append(",");



value.append(str[18]);

value.append(".0");

value.append(",");



value.append(str[14]);

value.append(":");

if (entityType==location[0]){

value.append(pmLocation[0]);

near=true;

}else if (entityType==location[1]){

value.append(pmLocation[1]);

near=false;

}

value.append(",");



String pmMeasurement_1=null;

String pmMeasurement_2=null;

String result=null;



if(!keyList.contains(keyStr)){

pmMeasurement_1=getPMMeasurement(pmParameters,str, true,near,pmLocation,location);

value.append(pmMeasurement_1);



result=value.toString();



}else{

pmMeasurement_2=getPMMeasurement(pmParameters,str, false,near,pmLocation,location);

}



if(!keyList.contains(keyStr)){



keyList.add(index,keyStr);

valueList.add(index,result);

index++;

}else{

int position=keyList.indexOf(keyStr);

String temp=(String)valueList.get(position);

String[] tempArray=temp.split(",");

valueList.remove(position);

StringBuffer tempBuffer=new StringBuffer();

for(int i=0;i<(tempArray.length-4);i++){

tempBuffer.append(tempArray[i]);

tempBuffer.append(",");

}



tempBuffer.append(pmMeasurement_2);

valueList.add(position, tempBuffer.toString());



}







}//if

}//end while





if((startDate != endDate) || (start_week_of_year != end_week_of_year)){



logger.info(HDR +"Start and End Not Equal");



if(granularity[0].equalsIgnoreCase("15min")){



endfileName.append(eyearStr);

endfileName.append("_");

endfileName.append(emonthStr);

endfileName.append("_");

endfileName.append(edateStr);

endfileName.append("_");

endfileName.append("15M");

endfileName.append("_");

if(ne_type<=9){

endfileName.append("0");

endfileName.append(ne_type);

}else{

endfileName.append(ne_type);

}

endfileName.append(".ppm");



}else if(granularity[0].equalsIgnoreCase("24H")){



endfileName.append(eyearStr);

endfileName.append("_");

if(end_week_of_year <=9){

endfileName.append("0");

endfileName.append(end_week_of_year);

}else{

endfileName.append(end_week_of_year);

}



endfileName.append("_");

endfileName.append("24H");

endfileName.append("_");

if(ne_type<=9){

endfileName.append("0");

endfileName.append(ne_type);

}else{

endfileName.append(ne_type);

}

endfileName.append(".ppm");

}



logger.info(HDR+"endfileName "+endfileName);



path = "/var/ftp/PMFiles/marconi/" + endfileName;



logger.info(HDR+"path "+path);



File endfile=new File(path);

reader=new BufferedReader(new FileReader(endfile));

while((line = reader.readLine()) != null)

{



String[] testStr=line.split(REGEX1);



try{

int test=Integer.parseInt(testStr[testStr.length-1]);

}catch(Exception e){



String newLine= reader.readLine();



StringBuffer buffer=new StringBuffer(line);

buffer.append(newLine);

line=buffer.toString();



}





m=pattern.matcher(line);



boolean matchFound = m.find();

if (matchFound){

str=new String[m.groupCount()+1];

for (int i=0; i<=m.groupCount(); i++)

str[i]=m.group(i);

}



int neId=Integer.parseInt(str[2]);

int neType=Integer.parseInt(str[3]);

int shelfId=Integer.parseInt(str[4]);

int cardId=Integer.parseInt(str[6]);

int portId=Integer.parseInt(str[9]);

int indexId1=Integer.parseInt(str[10]);

int indexId2=Integer.parseInt(str[11]);

int indexId3=Integer.parseInt(str[12]);

int indexId4=Integer.parseInt(str[13]);

int entityType=Integer.parseInt(str[14]);

ParsePosition p=new ParsePosition(0);

Date time=dateFormat.parse(str[18],p);



if(((entityType==location[0]||entityType==location[1]))

&&(time.before(end) ||time.equals(end))

&& neId==ne_id && neType==ne_type && shelfId==shelf_id

&& indexId1==index1_id && indexId2==index2_id && indexId3==index3_id && indexId4==index4_id

&& cardId==card_id && portId ==port_id){





StringBuffer key=new StringBuffer();



for(int l=1;l<13;l++){



key.append(str[l]);

key.append(":");

}



key.append(str[18]);

key.append(".0");



String keyStr=key.toString();



StringBuffer value=new StringBuffer();



for(int k=0;k<4;k++){

value.append(name[k].value);

value.append(",");

}



value.append(granularity[0]);

value.append(",");



value.append(layerRate[0]);

value.append(",");



value.append(str[18]);

value.append(".0");

value.append(",");



value.append(str[14]);

value.append(":");

if (entityType==location[0]){

value.append(pmLocation[0]);

near=true;

}else if (entityType==location[1]){

value.append(pmLocation[1]);

near=false;

}

value.append(",");



String pmMeasurement_1=null;

String pmMeasurement_2=null;

String result=null;



if(!keyList.contains(keyStr)){

pmMeasurement_1=getPMMeasurement(pmParameters,str, true,near,pmLocation,location);

value.append(pmMeasurement_1);



result=value.toString();



}else{

pmMeasurement_2=getPMMeasurement(pmParameters,str, false,near,pmLocation,location);

}



if(!keyList.contains(keyStr)){



keyList.add(index,keyStr);

valueList.add(index,result);

index++;

}else{

int position=keyList.indexOf(keyStr);

String temp=(String)valueList.get(position);

String[] tempArray=temp.split(",");

valueList.remove(position);

StringBuffer tempBuffer=new StringBuffer();

for(int i=0;i<(tempArray.length-4);i++){

tempBuffer.append(tempArray[i]);

tempBuffer.append(",");

}

tempBuffer.append(pmMeasurement_2);

valueList.add(position, tempBuffer.toString());



}



}

}



}



}catch(FileNotFoundException e){

logger.warn(HDR+e.getMessage());

logger.warn("", e);

}catch(IndexOutOfBoundsException e){

logger.warn(HDR+e.getMessage());

logger.warn("", e);

}catch(PatternSyntaxException e){

logger.warn(HDR+e.getMessage());

logger.warn("", e);

}catch(IOException e){

logger.warn(HDR+e.getMessage());

logger.warn("", e);

}catch(NullPointerException e){

logger.warn(HDR+e.getMessage());

logger.warn("", e);

}catch(Exception e){

logger.warn(HDR+e.getMessage());

logger.warn("", e);

}finally{

try{

keyList=null;

if (reader!=null)

reader.close();

}catch(IOException e){

logger.warn(HDR+e.getMessage());

logger.warn("", e);

}

}



for(int k=0;k<valueList.size();k++)

logger.info("Final valueList Returned is " +valueList.get(k));

logger.info(HDR+"Returned valueList ");

return valueList;



}
Aug 10 '07 #8
JosAH
11,448 Expert 8TB
this is the method.....sry its too big Jos
It sure is ;-) What ends up in the log output? Does the log output flush itself
after a single line is written to it?

kind regards,

Jos
Aug 10 '07 #9
jyohere
73
It sure is ;-) What ends up in the log output? Does the log output flush itself
after a single line is written to it?

kind regards,

Jos
The while loop is not executing only sometimes....it does not enter inside....when i
type reader.ready()....it gives false before the loop....wat could the problem ....can it be because of too much load in the server.....one more thing is that for every 15 minutes the file gets overwritten.....but if the file is not there it should have thrown file not found exception isn't it....pls help....have been spending time on this for quite a long time....give me the possible chances of error...
Aug 10 '07 #10
JosAH
11,448 Expert 8TB
The while loop is not executing only sometimes....it does not enter inside....when i
type reader.ready()....it gives false before the loop....wat could the problem ....can it be because of too much load in the server.....one more thing is that for every 15 minutes the file gets overwritten.....but if the file is not there it should have thrown file not found exception isn't it....pls help....have been spending time on this for quite a long time....give me the possible chances of error...
So another (external) process is fiddling with that file. I'm beginning to understand
while that entire while loop is skipped: suppose you open the file successfully,
then the file content is changed and your process can't read the (previous)
content anymore because it hadn't started reading yet.

Either make that other process lock the overwriting process; by using an (empty)
lock file on which both processes negoatiate or (this is hacking) make your
process try to reopen the entire thing if opening the file succeeded but the first
read did not.

Your two processes should use a locking mechanism though otherwise you're
asking for trouble (which you already experienced ;-)

kind regards,

Jos
Aug 10 '07 #11
jyohere
73
So another (external) process is fiddling with that file. I'm beginning to understand
while that entire while loop is skipped: suppose you open the file successfully,
then the file content is changed and your process can't read the (previous)
content anymore because it hadn't started reading yet.

Either make that other process lock the overwriting process; by using an (empty)
lock file on which both processes negoatiate or (this is hacking) make your
process try to reopen the entire thing if opening the file succeeded but the first
read did not.

Your two processes should use a locking mechanism though otherwise you're
asking for trouble (which you already experienced ;-)

kind regards,

Jos
the other process is a crontab entry in linux which will fetch the file from an other system and overwrite it.....i am asking about the load because when the file is of small size in the beginning it is working fine...but when the file size increases to say 3mb it is behaving differently....hope its clear for u now..
Aug 10 '07 #12
JosAH
11,448 Expert 8TB
the other process is a crontab entry in linux which will fetch the file from an other system and overwrite it.....i am asking about the load because when the file is of small size in the beginning it is working fine...but when the file size increases to say 3mb it is behaving differently....hope its clear for u now..
If the other process doesn't want to play that locking game all bets are off. You
could check (before you start reading) whether or not the file size is changing.
If so, don't read because the other process is writing. If it doesn't change, hope
for the best and start reading.

kind regards,

Jos
Aug 10 '07 #13
jyohere
73
If the other process doesn't want to play that locking game all bets are off. You
could check (before you start reading) whether or not the file size is changing.
If so, don't read because the other process is writing. If it doesn't change, hope
for the best and start reading.

kind regards,

Jos
I am testing the file putting it in a separate place.....let me try my luck
Aug 10 '07 #14
JosAH
11,448 Expert 8TB
I am testing the file putting it in a separate place.....let me try my luck
I wish you all the best of luck.

kind regards,

Jos
Aug 10 '07 #15
jyohere
73
thanks jos....i think u are right.....need to test more....wl let u know
Aug 10 '07 #16

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: Steven T. Hatton | last post by:
I haven't looked very closely, but from what I'm seeing, it looks like there are no buffered I/O streams in the Standard Library. There are stream buffers, but not buffered streams. I don't have...
9
by: kernelxu | last post by:
hi,everybody. I calling function setbuf() to change the characteristic of standsrd input buffer. some fragment of the progrem is: (DEV-C++2.9.9.2) #include <stdio.h> #include <stdlib.h> int...
5
by: Heriberto | last post by:
Hi, I'd like to know how to work with excel using C#. I known how to do it in Delphi but I new in C#. I just want a small exemple. And if anyone knows if there are diferrence working with excel...
4
by: pank7 | last post by:
hi everyone, I have a program here to test the file IO(actually output) with buffer turned on and off. What I want to see is that there will be obvious differece in time. Here I have an input...
1
by: Tom Bianchi | last post by:
Hi, is it possible to make a SplitContainer double buffered ? Deriving and setting the style in the constructor doesn't seem to work, maybe because it is composed by two normal Panels... ...
2
by: Karl | last post by:
Hey everyone! I've got a quick question on whether std::ifstream is buffered or not. The reason is that I have a homework assignment that requires me to benchmark copying files using different...
3
by: lenin42001 | last post by:
All help gratefully recieved. What exactly is a buffered reader? We know it reads bytes from a zip.file but can it also read input that has been put into the terminal-window? We are using BlueJ & it...
1
by: LiorO | last post by:
Hi, I need to implement a high performance file copying. The File.Copy method in .NET is fast enough however I need to control the speed since it should be performed in the background without...
8
by: zeeshan708 | last post by:
what is the difference between the buffered and unbuffered stream ??(e.g we say that cout is buffered and cerr is unbuffered stream) does that mean that the output sent to buffered stream have to go...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.