I need to read a file line by line using java.nio
, but nio
doesn\'t have a method like readline()
to read one, complete line at a time
It works for me....
public static void main(String[] args) throws IOException
{
RandomAccessFile aFile = new RandomAccessFile
("F:\\DetailsMy1.txt", "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1);
StringBuffer line = new StringBuffer();
while(inChannel.read(buffer) > 0)
{
buffer.flip();
for (int i = 0; i < buffer.limit(); i++)
{
char ch = ((char) buffer.get());
if(ch=='\r'){
System.out.print(line+"[EOL]");
line=new StringBuffer();
}else{
line.append(ch);
}
}
buffer.clear(); // do something with the data and clear/compact it.
}
inChannel.close();
aFile.close();
}