NioLineCount: Working

This commit is contained in:
Karsten Jeppesen
2021-04-14 18:42:18 +02:00
parent 0ad4c474bc
commit b458d7067d

View File

@@ -8,6 +8,7 @@ import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Semaphore;
/**
*
@@ -20,36 +21,54 @@ import java.nio.file.StandardOpenOption;
public class NioLineCount {
static int theCount = 0;
// A 0 means that you will be waited until signalled
static Semaphore partialReadGate = new Semaphore(1);
static boolean doContinue = true;
static long readPosition = 0;
private static int lineCount(String thePath, boolean doDance){
if ( ! doDance ) return -1;
ByteBuffer buffer = ByteBuffer.allocate(1024);
long myPosition = 0;
Path myPath = Paths.get( thePath );
try {
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(myPath, StandardOpenOption.READ);
fileChannel.read(buffer, myPosition, buffer, new CompletionHandler<Integer,ByteBuffer>() {
while ( doContinue ) {
try {
// In the end we will be waiting here
partialReadGate.acquire();
if ( ! doContinue ) return theCount;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileChannel.read(buffer, readPosition, buffer, new CompletionHandler<Integer,ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("Result = " + result + " Limit = " + attachment.limit());
// System.out.println("Result = " + result + " Limit = " + attachment.limit());
if ( result != -1 ) {
attachment.flip();
//System.out.println(Charset.defaultCharset().decode(buffer));
byte[] data = new byte[attachment.limit()];
attachment.get( data );
System.out.println(new String(data));
System.out.println(">> " + data.toString());
//System.out.println(new String(data));
for (int i = 0; i < data.length; i++ ) {
if ( data[i] == '\n' )
theCount++;
//System.out.println("data: " + data[i]);
}
// System.out.println("position: " + readPosition + " Count: " + theCount);
readPosition += data.length;
attachment.clear();
} else {
doContinue = false;
}
partialReadGate.release();
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();