ロックを取得してファイルにWriterで書き込む処理のサンプル
public static void writeWithNoWaitLock(String filename) throws IOException { FileOutputStream fos = null; Writer writer = null; FileChannel channel = null; try { fos = new FileOutputStream(filename); writer = new BufferedWriter(new OutputStreamWriter(fos)); channel = fos.getChannel(); FileLock lock = channel.lock(); try { writer.write("some string..."); writer.flush(); } finally { lock.release(); } } finally { closeIgnoringException(writer); closeIgnoringException(fos); closeIgnoringException(channel); } } private static void closeIgnoringException(Closeable c) { if ( c != null ) { try { c.close(); } catch (IOException e) { // no-opp } } }
FileLock lock = FileChannel.tryLock()でFileLockを取得すると、ロック失敗時はnullが戻されます。これにより再試行が行えます。
読み込み時は、
FileInputStream fis = new FileInputStream(filename);
FileChannel channel = fis.getChannel();
読み書きは時は、
RandomAccessFile file = new RandomAccessFile(filename, "rw"); FileChannel channel = file.getChannel();