Non-blocking (NIO) reading of lines

前端 未结 9 761
滥情空心
滥情空心 2020-12-31 07:01

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

9条回答
  •  伪装坚强ぢ
    2020-12-31 07:43

    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();
        }
    

提交回复
热议问题