I wrote a function for iterating over a large file with performance in mind. It takes in an InputStream
and reads until it reaches the end of the file. Whenever it detects an end of line it will call the UnsafeConsumer#accept
with the line.
UnsafeConsumer
is the same asConsumer<T>
but has a throws declaration on accept functionstream
has to be closed outside the function
I am am not sure if this is the fastest way to do this. Is there anything different that I could do?
public static void fileLines(InputStream stream, UnsafeConsumer<String,IOException> cons) throws IOException{
StringBuilder lineBuild=new StringBuilder();
int character;
while(true){ //read file
while(true){ //read line
character=stream.read();
if(character==-1){
cons.accept(lineBuild.toString());
lineBuild.setLength(0);
return;
}
if(character=='\n'){
cons.accept(lineBuild.toString());
lineBuild.setLength(0);
character=stream.read();
if(character==-1) return;
else if(character!='\r'&&character!='\n') lineBuild.append((char)character);
break;
}
lineBuild.append((char)character);
}
}
}