60 likes | 134 Views
IO. Lecture 5. java.nio. New: Buffer management Channels File locking Memory mapping. java.nio: Buffers. “Buffer” a well-known concept, but is often home brewed by developers. They are now predefined and performance-optimized.
E N D
IO Lecture 5
java.nio • New: • Buffer management • Channels • File locking • Memory mapping
java.nio: Buffers • “Buffer” a well-known concept, but is often home brewed by developers. They are now predefined and performance-optimized. • ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, MappedByteBuffer, ShortBuffer
java.nio: Channels • A flexible concept that includes any open connection to a program entity. • DatagramChannel: when working with datagram sockets (UDP). • SocketChannel: for use with TCP/IP sockets. • FileChannel: for reading, writing, mapping, manipulating files. • Pipe.SinkChannel/-SourceChannel: for use with the writable/readable end of a pipe.
java.nio: Memory mapping • MappedByteBuffer • We may map the contents of a file into a region of memory. • File locking necessary
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.FileNotFoundException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class ReadPrimes { public static void main(String[] args) { File aFile = new File("primes.bin"); FileInputStream inFile = null; try { inFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel inChannel = inFile.getChannel(); final int PRIMECOUNT = 6; ByteBuffer buf = ByteBuffer.allocate(8*PRIMECOUNT); long[] primes = new long[PRIMECOUNT]; try { while(inChannel.read(buf) != -1) { ((ByteBuffer)(buf.flip())).asLongBuffer().get(primes); // List the primes read on the same line System.out.println(); for(long prime : primes) System.out.printf("%10d", prime); buf.clear(); // Clear the buffer for the next read } System.out.println("\nEOF reached."); inFile.close(); // Close the file and the channel } catch(IOException e) { e.printStackTrace(System.err); System.exit(1); } System.exit(0); } } New I/O Example (ReadPrimes) From the channel, read data and save to the buffer Channel Setup You also need to read the “PrimesToFile.java” which prints prime numbers to the file. Buffer Setup Java Programming