Looping over InputStream truncating data
readLine
for DataInputStream
is deprecated. You may try wrapping it with a BufferedReader
:
try
{
String line;
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( dataInputStream ) );
while( (line = bufferedReader.readLine()) != null )
{
System.out.printf("%s\n", line);
}
}
catch( IOException e )
{
System.err.println( "Error: " + e );
}
Also, I`m not sure, that it is a good idea to use available() due to this specification:
* <p>Note that this method provides such a weak guarantee that it is not very useful in
* practice.
idigyourpast
Updated on June 24, 2022Comments
-
idigyourpast almost 2 years
So this is a very simple problem with a simple solution that I'm just not seeing:
I'm trying to get a list of data through an InputStream, looping until I reach the end of the stream. On each iteration, I print the next line of text being passed through the InputStream. I have it working but for one small problem: I'm truncating the first character of each line.
Here's the code:
while (dataInputStream.read() >= 0) { System.out.printf("%s\n", dataInputReader.readLine()); }
And the output:
classpath project est.txt
Now, I know what's going on here: the
read()
call in mywhile
loop is taking the first char on each line, so when the line gets passed into the loop, that char is missing. The problem is, I can't figure out how to set up a loop to prevent that.I think I just need a new set of eyes on this.