NioLineCount: WIP. Non-blocking IO
Not working yet
This commit is contained in:
74
NioLineCount/src/NioLineCount.java
Normal file
74
NioLineCount/src/NioLineCount.java
Normal file
@@ -0,0 +1,74 @@
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.channels.AsynchronousFileChannel;
|
||||
import java.nio.channels.CompletionHandler;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.OpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @author KAJE
|
||||
*
|
||||
*/
|
||||
public class NioLineCount {
|
||||
|
||||
static int theCount = 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>() {
|
||||
@Override
|
||||
public void completed(Integer result, ByteBuffer attachment) {
|
||||
System.out.println("Result = " + result + " Limit = " + attachment.limit());
|
||||
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());
|
||||
for (int i = 0; i < data.length; i++ ) {
|
||||
if ( data[i] == '\n' )
|
||||
theCount++;
|
||||
//System.out.println("data: " + data[i]);
|
||||
}
|
||||
attachment.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, ByteBuffer attachment) {
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return theCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args){
|
||||
long startTime = System.nanoTime();
|
||||
lineCount("", false);
|
||||
long dryRun = System.nanoTime() - startTime;
|
||||
startTime = System.nanoTime();
|
||||
int lines = lineCount("input.txt", true);
|
||||
long stopTime = System.nanoTime();
|
||||
System.out.println("Lines: " + String.valueOf(lines));
|
||||
System.out.println("Time it took: " + (stopTime - startTime - dryRun) + " " + dryRun);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user