Et
asked on
EOF indicator while using an InputStreamReader
Hi! I have to read an ASCII file, represented by a FileInputStream, through an InputStreamReader. I use the read() method explained below :
int read(char[] cbuf, int off, int len)
Read characters into a portion of an array.
I encounter an annoying problem, I don't know how to detect the end of file, as this method doesn't throw an EOFException. Also, the only way to detect the end of line was to read the stream char by char, waiting to find the '\n' indicator.
So, any idea to read an ASCII file line by line and detect the end of file, without knowing how many lines there are?
Thanx a lot!
int read(char[] cbuf, int off, int len)
Read characters into a portion of an array.
I encounter an annoying problem, I don't know how to detect the end of file, as this method doesn't throw an EOFException. Also, the only way to detect the end of line was to read the stream char by char, waiting to find the '\n' indicator.
So, any idea to read an ASCII file line by line and detect the end of file, without knowing how many lines there are?
Thanx a lot!
I think it will throw an EOFException. The documentation says it throws IOException. I'm pretty sure that just short for indicating it could throw a number of IOExceptions, and EOFException would be one of them. Try it and see.
ASKER
I also thought about this, but it doesn't work like the ObjectOutputStream class, which readObject() method doesn't explicitly throw an EOFException but if you catch it before the IOException(), it works... here's my method by the way :
private String getLine( InputStreamReader reader ) throws EOFException, IOException, Exception
{
String charRead = new String();
char[] buffer = new char[1];
int i = 1;
try
{
reader.read( buffer, 0, 1 );
while( buffer[0] != '\n' )
{
charRead = charRead + buffer[0];
i++;
reader.read( buffer, 0, 1 );
}
return charRead + '\n';
}
catch(EOFException eofEx)
{
throw eofEx;
}
catch(IOException IOEx)
{
throw IOEx;
}
catch(Exception e)
{
throw e;
}
}
private String getLine( InputStreamReader reader ) throws EOFException, IOException, Exception
{
String charRead = new String();
char[] buffer = new char[1];
int i = 1;
try
{
reader.read( buffer, 0, 1 );
while( buffer[0] != '\n' )
{
charRead = charRead + buffer[0];
i++;
reader.read( buffer, 0, 1 );
}
return charRead + '\n';
}
catch(EOFException eofEx)
{
throw eofEx;
}
catch(IOException IOEx)
{
throw IOEx;
}
catch(Exception e)
{
throw e;
}
}
ASKER
By the way, when I reach the last line, it doesn't find the '\n' ()even if I added it manually) character so it loops infinitely...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Geeez! Seems I can't read... sorry for that stupid question!!!!