import java.nio.*; import java.nio.channels.*; import java.io.*; public class FileChannelTest5 { public FileChannelTest5(String filename, int position, int size, boolean shareFlag) { access(filename, position, size, shareFlag); } private void access(String filename, int position, int size, boolean shareFlag){ try{ RandomAccessFile raFile = new RandomAccessFile(filename, "rw"); FileChannel channel = raFile.getChannel(); // Acquire Exclusive Lock System.out.println("Acquire Lock."); FileLock lock = channel.lock(position, size, shareFlag); System.out.println("Lock: " + lock); ByteBuffer buffer = ByteBuffer.allocate(size); channel.position(position); channel.read(buffer); System.out.println("Read " + size + " bytes from position: " + position); javax.swing.JOptionPane.showMessageDialog(null, "Release Lock?"); lock.release(); channel.close(); System.exit(0); }catch(FileNotFoundException ex){ ex.printStackTrace(); }catch(IOException ex){ ex.printStackTrace(); } } public static void main(String[] args){ new FileChannelTest5(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]), args[3].equalsIgnoreCase("shared") ? true : false); } }