1 / 56

JAVA Programcılığı 4.2.2

JAVA Programcılığı 4.2.2. Ali R+ SARAL. Ders Planı 4.2.2. Chapter 11: Reading Files File Read Operations File Channel Read Operations Reading a Text File Reading Binary Data. Ders Planı 4.2.2. Reading Mixed Data Copying Files Random Access to a File

Download Presentation

JAVA Programcılığı 4.2.2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JAVA Programcılığı 4.2.2 Ali R+ SARAL

  2. Ders Planı 4.2.2 • Chapter 11: Reading Files • File Read Operations • File Channel Read Operations • Reading a Text File • Reading Binary Data

  3. Ders Planı 4.2.2 • Reading Mixed Data • Copying Files • Random Access to a File • Read/Write Operations with a Single File Channel • Memory-Mapped Files

  4. File Read Operations • You obtain a FileChannel object from a file stream, • and use the channel to read data from the file into one or more buffers.

  5. Creating File Input Streams FileInputStream inputFile = null; // Place to store the input stream reference try { inputFile = new FileInputStream(“C:/Beg Java Stuff/myFile.txt”); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); }

  6. Creating File Input Streams File aFile = new File(“C:/Beg Java Stuff/myFile.txt”); FileInputStream inputFile = null; //Place to store the input stream reference try { inputFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); }

  7. Creating File Input Streams File aFile = new File(“C:/Beg Java Stuff/myFile.text”); FileInputStream inputFile1 = null; // Place to store an input stream reference FileDescriptor fd = null; // Place to store the file descriptor try { // Create the stream opened to write inputFile1 = new FileInputStream(aFile); fd = inputFile1.getFD(); // Get the file descriptor for the file } catch(IOException e) { // For IOException or FileNotFoundException e.printStackTrace(System.err); System.exit(1); } // You can now create another input stream for the file from the file descriptor... FileInputStream inputFile2 = new FileInputStream(fd);

  8. File Channel Read Operations • You obtain a reference to a FileChannel object that you can use to read a file by calling the • getChannel() method of a FileInputStream object. • read(ByteBuffer buf) Tries to read buf.remaining() bytes (equivalent to limit-position bytes) from the file into the buffer, buf, starting at the buffer’s current position. • read(ByteBuffer[] buffers) Tries to read bytes into each of the buffers in the buffers array in sequence. • read(ByteBuffer[] buffers, int offset, int length)

  9. File Channel Read Operations • All three methods can throw exceptions of any of the following types: • NonReadableChannelException Thrown if the file was not opened for reading • ClosedChannelException Thrown if the channel is closed • AsynchronousCloseException Thrown if the channel is closed by another thread while the read operation is in progress • ClosedByInterruptException Thrown if another thread interrupts the current thread while the read operation is in progress • IOException Thrown if some other I/O error occurs

  10. File Channel Read Operations try { inChannel.position(0); // Set file position to first byte } catch(IOException e) { e.printStackTrace(); } • This method will throw a ClosedChannelException if the channel is closed, or an IOException if some other error occurs, so you need to put the call in a try block. • Calling the position() method with no argument specified returns the current file position.

  11. File Channel Read Operations

  12. Reading a Text File File aFile = new File(“C:/Beg Java Stuff/charData.txt”); FileInputStream inFile = null; try { inFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel inChannel = inFile.getChannel();

  13. Reading a Text File ByteBuffer buf = ByteBuffer.allocate(48); try { while(inChannel.read(buf) != -1) { // Code to extract the data that was read into the buffer... buf.clear(); // Clear the buffer for the next read } System.out.println(“EOF reached.”); } catch(IOException e) { e.printStackTrace(System.err); System.exit(1); }

  14. Getting Data from the Buffer • After each read operation, the buffer’s position will point to the byte following the last byte that was read. • Before you attempt to extract any data from the buffer, you therefore need to flip the buffer to reset the position back to the beginning of the data, and the limit to the byte following the last byte of data that was read. buf.flip(); StringBuffer str = new StringBuffer(buf.remaining()/2); while(buf.hasRemaining()) str.append(buf.getChar()); System.out.println(“String read: “+ str.toString());

  15. Getting Data from the Buffer • This approach works okay, but a better way is to use a view buffer of type CharBuffer. • The toString() method for the CharBuffer object will give you the string that it contains directly. • Indeed, you can boil the whole thing down to a single statement: • System.out.println(“String read: “ + ((ByteBuffer)(buf.flip())).asCharBuffer().toString());

  16. Try It Out Reading Text from a File 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 ReadAString { public static void main(String[] args) { File aFile = new File(“C:/Beg Java Stuff/charData.txt”); FileInputStream inFile = null; try { inFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel inChannel = inFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48); try { while(inChannel.read(buf) != -1) { System.out.println(“String read: “ + ((ByteBuffer)(buf.flip())).asCharBuffer().toString()); buf.clear(); // Clear the buffer for the next read } System.out.println(“EOF reached.”); inFile.close(); // Close the file and the channel } catch(IOException e) { e.printStackTrace(System.err); System.exit(1); } System.exit(0); } }

  17. Reading Binary Data File aFile = new File(“C:/Beg Java Stuff/primes.bin”); FileInputStream inFile = null; try { inFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel inChannel = inFile.getChannel();

  18. Reading Binary Data final int PRIMECOUNT = 6; // Number of primes to read at a time ByteBuffer buf = ByteBuffer.allocate(8*PRIMECOUNT); You can then read the primes in a while loop inside a try block: long[] primes = new long[PRIMECOUNT]; try { while(inChannel.read(buf) != -1) { // Access the primes via a view buffer of type LongBuffer... // Output the primes read... buf.clear(); // Clear the buffer for the next read } System.out.println(“EOF reached.”); inFile.close(); // Close the file and the channel } catch(IOException e) { e.printStackTrace(System.err); System.exit(1); }

  19. Reading Binary Data • You can create a view buffer of type LongBuffer that will help you get at the primes once a block of data has been read from the file. You obtain the view buffer by calling the asLongBuffer() method for the byte buffer, buf. • get() Extracts a single value of type long from the buffer at the current position and returns it. • get(int index) Extracts a single value of type long from the buffer position specified by the argument and returns it. • get(long[] values) Extracts values.length values of type long from the buffer starting at the current position and stores them in the array values. • get(long[] values, int offset, int length) Extracts length values of type long from the buffer starting at the current position and stores them in the values array, starting at values[offset]. LongBuffer longBuf = ((ByteBuffer)(buf.flip())).asLongBuffer(); System.out.println(); // Newline for the buffer contents while(longBuf.hasRemaining()) { // While there are values System.out.print(“ “ + longBuf.get()); // output them on the same line }

  20. Try It Out Reading a Binary File 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(“C:/Beg Java Stuff/primes.bin”); FileInputStream inFile = null; try { inFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); }

  21. Try It Out Reading a Binary File 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); } }

  22. Reading Mixed Data • Of course, the big problem is that you don’t know ahead of time exactly how long the strings are. • You can read the string length in the first read operation, then read the string and the binary prime value in the next. • You can set up a sizable byte buffer of an arbitrary capacity and just fill it with bytes from the file. You can then sort out what you have in the buffer.

  23. Reading Mixed Data • To read the string length you need a byte buffer with a capacity to hold a single value of type double: ByteBuffer lengthBuf = ByteBuffer.allocate(8); int strLength = 0; // Stores the string length ByteBuffer buf = null; //Stores a reference to the second byte buffer byte[] strChars = null; //Stores a reference to an array to hold the string

  24. Reading Mixed Data • Since you need two read operations to get at all the data for a single prime, your strategy for reading the entire file will have to provide for this. • A good approach would be to put both read operations in an indefinite loop and use a break statement to exit the loop when you hit the end-of-file (EOF).

  25. Reading Mixed Data while(true) { if(inChannel.read(lengthBuf) == -1) // Read the string length, if it’s EOF break; // exit the loop lengthBuf.flip(); strLength = (int)lengthBuf.getDouble(); // Extract length & convert to int buf = ByteBuffer.allocate(2*strLength+8); // Buffer for string & prime if(inChannel.read(buf) == -1) { // Read string & binary prime value assert false; // Should not get here! break; // Exit loop on EOF } buf.flip(); strChars = new byte[2*strLength]; // Create the array for the string buf.get(strChars); // Extract string & binary prime value System.out.printf(“String length: %3s String: %-12s Binary Value: %3d%n”, strLength, ByteBuffer.wrap(strChars).asCharBuffer(),buf.getLong()); lengthBuf.clear(); // Clear the buffer for the next read }

  26. Try It Out Reading Mixed Data from a File import java.io.FileInputStream; import java.io.IOException; import java.io.File; import java.io.FileNotFoundException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class ReadPrimesMixedData { public static void main(String[] args) { File aFile = new File(“C:/Beg Java Stuff/primes.txt”); FileInputStream inFile = null; try { inFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); }

  27. Try It Out Reading Mixed Data from a File FileChannel inChannel = inFile.getChannel(); try { ByteBuffer lengthBuf = ByteBuffer.allocate(8); int strLength = 0; // Stores the string length ByteBuffer buf = null; // Stores a reference to the second byte buffer byte[] strChars = null; // A reference to an array to hold the string while(true) { if(inChannel.read(lengthBuf) == -1) // Read the string length, break; // if its EOF exit the loop lengthBuf.flip(); // Extract the length and convert to int strLength = (int)lengthBuf.getDouble(); // Buffer for the string & the prime buf = ByteBuffer.allocate(2*strLength+8);

  28. Try It Out Reading Mixed Data from a File if(inChannel.read(buf) == -1) { // Read the string & binary prime value assert false; // Should not get here! break; // Exit loop on EOF } buf.flip(); strChars = new byte[2*strLength]; // Create the array for the string buf.get(strChars); // Extract the string System.out.printf(“String length: %3s String: %-12s Binary Value: %3d%n”, strLength, byteBuffer.wrap(strChars).asCharBuffer(),buf.getLong()); lengthBuf.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); } }

  29. Compacting a Buffer • 1. Read from the file into the buffer. • 2. Extract the string length, the string, and the binary prime value from the buffer repeatedly until no more complete values are available. • 3. Shift any bytes that are left over in the buffer back to the beginning of the buffer. • These will be some part of a complete set of the string length, the string, and the binary prime value. • Go back to point 1 to read more from the file.

  30. Compacting a Buffer

  31. Try It Out Reading into a Large Buffer (missing?) import java.io.FileInputStream; import java.io.IOException; import java.io.File; import java.io.FileNotFoundException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class ReadPrimesMixedData2 { public static void main(String[] args) { File aFile = new File(“C:/Beg Java Stuff/primes.txt”); FileInputStream inFile = null; try { inFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel inChannel = inFile.getChannel(); try { ByteBuffer buf = ByteBuffer.allocateDirect(1024); buf.position(buf.limit()); // Set the position for the loop operation int strLength = 0; // Stores the string length byte[] strChars = null; // Array for string

  32. Try It Out Reading into a Large Buffer while(true) { if(buf.remaining() < 8) { // Verify enough bytes for string length if(inChannel.read(buf.compact()) == -1) break; buf.flip(); } strLength = (int)buf.getDouble(); // Verify enough bytes for complete string if(buf.remaining()<2*strLength) { if(inChannel.read(buf.compact()) == -1) break; buf.flip(); } strChars = new byte[2*strLength]; buf.get(strChars); if(buf.remaining()<8) { // Verify enough bytes for prime value if(inChannel.read(buf.compact()) == -1) break; buf.flip(); } System.out.printf(“String length: %3s String: %-12s Binary Value: %3d%n”, strLength, ByteBuffer.wrap(strChars).asCharBuffer(),buf.getLong()); } 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); } }

  33. Copying Files • it is a useful way of demonstrating how a file channel for any input file can transfer data directly to a file channel for an output file without involving explicit buffers. • transferTo(long position, WritableByteChannel dst) Attempts to transfer count bytes from this long count, channel to the channel dst. Bytes are read from this channel starting at the file position specified by position. • transferFrom(ReadableByteChannel src, long count) Attempts to transfer count bytes to this long position, channel from the channel src. Bytes are written to this channel starting at the file position specified by position.

  34. Copying Files • IllegalArgumentException Thrown if either count or position is negative • NonReadableChannelException Thrown if the operation attempts to read from a channel that was not opened for reading • NonWritableChannelException Thrown if the operation attempts to write to a channel that was not opened for writing • ClosedChannelException Thrown if either channel involved in the operation is closed • AsynchronousCloseException Thrown if either channel is closed by another thread while the operation is in progress • ClosedByInterruptException Thrown if another thread interrupts the current thread while the operation is in progress • IOException Thrown if some other I/O error occurs

  35. Try It Out Direct Data Transfer between Channels (missing) // Method to create a unique backup File object public static File createBackupFile(File aFile) { aFile = aFile.getAbsoluteFile(); // Ensure you have an absolute path File parentDir = new File(aFile.getParent()); // Get the parent directory String name = aFile.getName(); // Get the file name int period = name.indexOf(‘.’); // Find the extension separator if(period == -1) { // If there isn’t one period = name.length(); // set it to the end of the string } String nameAdd = “_backup”; // String to be appended // Create a File object that is unique File backup = aFile; while(backup.exists()) { // If the name already exists... name = backup.getName(); // Get the current name of the file backup = new File(parentDir, name.substring(0,period) // add _backup again + nameAdd + name.substring(period)); period += nameAdd.length(); // Increment separator index } return backup; }

  36. Try It Out Direct Data Transfer between Channels import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.channels.FileChannel; public class FileCopy { public static void main(String[] args) { if(args.length==0) { System.out.println(“No file to copy. Application usage is:\n”+ “java -classpath . FileCopy \”filepath\”” ); System.exit(1); } File fromFile = new File(args[0]); if(!fromFile.exists()) { System.out.printf(“File to copy, %s, does not exist.”, fromFile.getAbsolutePath()); System.exit(1); } File toFile = createBackupFile(fromFile); FileInputStream inFile = null; FileOutputStream outFile = null; try { inFile = new FileInputStream(fromFile); outFile = new FileOutputStream(toFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); assert false; }

  37. Try It Out Direct Data Transfer between Channels FileChannel inChannel = inFile.getChannel(); FileChannel outChannel = outFile.getChannel(); try { int bytesWritten = 0; long byteCount = inChannel.size(); while(bytesWritten<byteCount) { bytesWritten += inChannel.transferTo(bytesWritten, byteCount-bytesWritten, outChannel); } System.out.printf(“File copy complete. %d bytes copied to %s%n”,byteCount, toFile.getAbsolutePath()); inFile.close(); outFile.close(); } catch(IOException e) { e.printStackTrace(System.err); System.exit(1); } System.exit(0); } // Code for createBackupFile() goes here... }

  38. Random Access to a File • You can already read from or write to a file at random. The FileChannel class defines both a read() and a write() method that operate at a specified position in the file: • read(ByteBuffer buf, long position) Reads bytes from the file into buf in the same way as you have seen previously except that bytes are read starting at the file position specified by the second argument. • write(ByteBuffer buf, long position) Writes bytes from buf to the file in the same way as you have seen previously except that bytes are written starting at the file position specified by the second argument.

  39. Try It Out Reading a File Randomly import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class RandomFileRead { public static void main(String[] args) { File aFile = new File(“C:/Beg Java Stuff/primes.bin”); FileInputStream inFile = null; FileOutputStream outFile = null; try { inFile = new FileInputStream(aFile); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); }

  40. Try It Out Reading a File Randomly FileChannel inChannel = inFile.getChannel(); final int PRIMESREQUIRED = 10; ByteBuffer buf = ByteBuffer.allocate(8*PRIMESREQUIRED); long[] primes = new long[PRIMESREQUIRED]; int index = 0; // Position for a prime in the file try { // Count of primes in the file final int PRIMECOUNT = (int)inChannel.size()/8; // Read the number of random primes required for(int i = 0 ; i<PRIMESREQUIRED ; i++) { index = 8*(int)(PRIMECOUNT*Math.random()); inChannel.read(buf, index); // Read the value buf.flip(); primes[i] = buf.getLong(); // Save it in the array buf.clear(); } // Output the selection of random primes 5 to a line in field width of 12

  41. Try It Out Reading a File Randomly int count = 0; // Count of primes written for(long prime : primes) { System.out.printf(“%12d”, prime); if(++count%5 == 0) { System.out.println(); } } inFile.close(); // Close the file and the channel } catch(IOException e) { e.printStackTrace(System.err); System.exit(1); } System.exit(0); } }

  42. Try It Out Reading and Writing a File Randomly import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class RandomReadWrite { public static void main(String[] args){ File aFile = new File(“C:/Beg Java Stuff/primes_backup.bin”); FileInputStream inFile = null; FileOutputStream outFile = null; try { inFile = new FileInputStream(aFile); outFile = new FileOutputStream(aFile, true); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel inChannel = inFile.getChannel(); FileChannel outChannel = outFile.getChannel(); final int PRIMESREQUIRED = 10; ByteBuffer buf = ByteBuffer.allocate(8); long[] primes = new long[PRIMESREQUIRED]; int index = 0; // Position for a prime in the file final long REPLACEMENT = 99999L; // Replacement for a selected prime

  43. Try It Out Reading and Writing a File Randomly try { final int PRIMECOUNT = (int)inChannel.size()/8; System.out.println(“Prime count = “+PRIMECOUNT); for(int i = 0 ; i<PRIMESREQUIRED ; i++) { index = 8*(int)(PRIMECOUNT*Math.random()); inChannel.read(buf, index); // Read at a random position buf.flip(); // Flip the buffer primes[i] = buf.getLong(); // Extract the prime buf.flip(); // Flip to ready for insertion buf.putLong(REPLACEMENT); // Replacement into buffer buf.flip(); // Flip ready to write outChannel.write(buf, index); // Write the replacement to file buf.clear(); // Reset ready for next read } int count = 0; // Count of primes written for(long prime : primes) { System.out.printf(“%12d”, prime); if(++count%5 == 0) { System.out.println(); } } inFile.close(); // Close the file and the channel outFile.close(); } catch(IOException e) { e.printStackTrace(System.err); System.exit(1); } System.exit(0); } }

  44. Read/Write Operations with a Single File Channel • If you want to be able to read from and write to a file using a single channel, you must use the channel provided by a RandomAccessFile object. A RandomAccessFile object is not related to the other file stream classes since its only base class is Object. • “r” Indicates that you just want to read the file. In this mode the file cannot be written. • “rw” Indicates that you want to open the file to allow both read and write operations. • “rwd” Indicates that you want to allow both read and write operations but you want all write operations to force immediate writing of data to the device. • “rws” Indicates that you want to allow both read and write operations but you want all write operations to force immediate writing of data and metadata (such as the file length) to the device.

  45. Read/Write Operations with a Single File Channel • To create a RandomAccessFile object, you could write: File myPrimes = new File(“c:/Beg Java Stuff/primes.bin”); RandomAccessFile primesFile = null; try { primesFile = new RandomAccessFile(myPrimes, “rw”); } catch(FileNotFoundException e) { e.printStackTrace(System.err); assert false; } FileChannel ioChannel = primesFile.getChannel();

  46. Memory-Mapped Files • A memory-mapped file is a file that has its contents mapped into an area of virtual memory in your computer. • This enables you to reference or update the data in the file directly without performing any explicit file read or write operations on the physical file yourself. • map(int mode, long size) Maps a region of the channel’s file to a buffer of type long position, MappedByteBuffer. The file region that is mapped starts at position in the file and is of length size bytes.

  47. Memory-Mapped Files • force() If the buffer was mapped in MapMode.READ_WRITE mode, this method forces any changes made to the buffer’s contents to be written to the file and returns a reference to the buffer. For buffers created with other access modes, this method has no effect. • load() Tries on a “best efforts” basis to load the contents of the buffer into memory and returns a reference to the buffer. • isLoaded() Returns true if it is likely that this buffer’s contents are available in physical memory and false otherwise.

  48. Try It Out Using a Memory-Mapped File import java.io.File; import java.io.RandomAccessFile; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import static java.nio.channels.FileChannel.MapMode.READ_WRITE; public class MemoryMappedFile { public static void main(String[] args) { File aFile = new File(“C:/Beg Java Stuff/primes_backup.bin”); RandomAccessFile ioFile = null; try { ioFile = new RandomAccessFile(aFile,”rw”); } catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel ioChannel = ioFile.getChannel(); final int PRIMESREQUIRED = 10; long[] primes = new long[PRIMESREQUIRED]; int index = 0; // Position for a prime in the file final long REPLACEMENT = 999999L; // Replacement for a selected prime

  49. Try It Out Using a Memory-Mapped File try { final int PRIMECOUNT = (int)ioChannel.size()/8; MappedByteBuffer buf = ioChannel.map(READ_WRITE, 0L,ioChannel.size()).load(); ioChannel.close(); // Close the channel for(int i = 0 ; i<PRIMESREQUIRED ; i++) { index = 8*(int)(PRIMECOUNT*Math.random()); primes[i] = buf.getLong(index); buf.putLong(index, REPLACEMENT); } int count = 0; // Count of primes written for(long prime : primes) { System.out.printf(“%12d”, prime); if(++count%5 == 0) { System.out.println(); } } ioFile.close(); // Close the file and the channel } catch(IOException e) { e.printStackTrace(System.err); System.exit(1); } System.exit(0); } }

  50. Locking a File • You need to take care that an external program does not modify a memory-mapped file that you are working with, especially if the file could be truncated externally while you are accessing it. • If you try to access a part of the file through a MappedByteBuffer that has become inaccessible because a segment has been chopped off the end of the file by another program, then the results are somewhat unpredictable.

More Related