當前位置: 首頁>>代碼示例>>Java>>正文


Java FileLock類代碼示例

本文整理匯總了Java中java.nio.channels.FileLock的典型用法代碼示例。如果您正苦於以下問題:Java FileLock類的具體用法?Java FileLock怎麽用?Java FileLock使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


FileLock類屬於java.nio.channels包,在下文中一共展示了FileLock類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: release

import java.nio.channels.FileLock; //導入依賴的package包/類
private static void release(String lockName, FileLock fileLock, File file, Closeable stream) {
    synchronized (LOCK_MAP) {
        if (fileLock != null) {
            try {
                LOCK_MAP.remove(lockName, fileLock.hashCode());
                ConcurrentHashMap<Integer, ProcessLock> locks = LOCK_MAP.get(lockName);
                if (locks == null || locks.isEmpty()) {
                    IOUtil.deleteFileOrDir(file);
                }

                if (fileLock.channel().isOpen()) {
                    fileLock.release();
                }
            } catch (Throwable ex) {
                LogUtil.e(ex.getMessage(), ex);
            } finally {
                IOUtil.closeQuietly(fileLock.channel());
            }
        }

        IOUtil.closeQuietly(stream);
    }
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:24,代碼來源:ProcessLock.java

示例2: incrementNextTaskId

import java.nio.channels.FileLock; //導入依賴的package包/類
public synchronized int incrementNextTaskId() {
	int toRet = -1;
	try {
		FileLock l = channel.lock();
		buffer.position(0);
		int current = buffer.getInt();
		buffer.position(0);
		current++;
		toRet = current;
		buffer.putInt(current);
		l.release();
	} catch (IOException e) {
		System.err.println("SharedSystemData, IOException : " + e.getMessage());
		e.printStackTrace();
	}
	
	return toRet;
}
 
開發者ID:bizzard4,項目名稱:MpiTaskFramework,代碼行數:19,代碼來源:SharedSystemData.java

示例3: zipFile

import java.nio.channels.FileLock; //導入依賴的package包/類
/**
 * Compactar uma arquivo.
 * @param inputFile informar o arquivo a ser compactado.
 * @param zipFilePath informar o nome e caminho zip.
 * @param iZipFile se necessário, informar uma {@link IZipFile}.
 * @throws IOException
 */
public static void zipFile(File inputFile, String zipFilePath, IZipFile iZipFile) throws IOException {
    FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath);
    ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
    ZipEntry zipEntry = new ZipEntry(inputFile.getName());
    zipOutputStream.putNextEntry(zipEntry);
    FileInputStream fileInputStream = new FileInputStream(inputFile);
    FileChannel fileChannel = fileInputStream.getChannel();
    FileLock fileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, /*shared*/true);
    long sizeToZip = fileInputStream.available();
    long sizeCompacted = 0;
    try {
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            sizeCompacted += bytesRead;
            zipOutputStream.write(buf, 0, bytesRead);
            if (iZipFile != null) iZipFile.progress(sizeToZip, sizeCompacted);
        }
    } finally {
        fileLock.release();
        zipOutputStream.closeEntry();
        zipOutputStream.close();
        fileOutputStream.close();
    }
}
 
開發者ID:brolam,項目名稱:OpenHomeAnalysis,代碼行數:33,代碼來源:OhaHelper.java

示例4: testOperationActions

import java.nio.channels.FileLock; //導入依賴的package包/類
public void testOperationActions() throws Exception { // #72397
    final NbModuleProject project = generateStandaloneModule("module");
    cgpi.setProject(project);
    DialogDisplayerImpl dd = (DialogDisplayerImpl) Lookup.getDefault().lookup(DialogDisplayer.class);
    FileObject lock = FileUtil.createData(project.getProjectDirectory(), "build/testuserdir/lock");
    RandomAccessFile raf = new RandomAccessFile(FileUtil.toFile(lock), "rw");
    FileLock lck = raf.getChannel().lock();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            ((ContextAwareAction) CommonProjectActions.deleteProjectAction()).createContextAwareInstance(Lookups.singleton(project)).actionPerformed(null);
        }
    });
    assertNotNull("warning message emitted", dd.getLastNotifyDescriptor());
    assertEquals("warning message emitted", dd.getLastNotifyDescriptor().getMessage(),
            Bundle.ERR_ModuleIsBeingRun());
    dd.reset();
    lck.release();
    raf.close();
    lock.delete();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            CommonProjectActions.deleteProjectAction().actionPerformed(null);
        }
    });
    assertNull("no warning message", dd.getLastNotifyDescriptor());
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:27,代碼來源:ModuleOperationsTest.java

示例5: writeFromSocketChannel

import java.nio.channels.FileLock; //導入依賴的package包/類
/**
	 * Will modify length of section if differnt amoutn actually written
	 * @param writeSection
	 * @param sourceChannel
	 * @throws IOException
	 */
	private void writeFromSocketChannel(Section writeSection, SocketChannel sourceChannel) throws IOException{
			synchronized (sourceChannel) {
				try (
						FileLock sectionLock = pieceChannel.lock(Integer.toUnsignedLong(writeSection.begin), Integer.toUnsignedLong(writeSection.length), false)
					)
					{
//					System.out.println("dksahfksjadh");
						int plz = writeSection.length;
						//writeSection.length = Math.toIntExact(pieceChannel.transferFrom(sourceChannel, Integer.toUnsignedLong(writeSection.begin), Integer.toUnsignedLong(writeSection.length)));
						ByteBuffer cant = ByteBuffer.allocate(plz);
						cant.clear();
						sourceChannel.read(cant);
						cant.rewind();
						pieceChannel.write(cant, writeSection.begin);
						
						
//						System.out.println("LENGTH ACTUALLY:  " + plz);

					};
			}
		
			
	}
 
開發者ID:jc0541,項目名稱:URTorrent,代碼行數:30,代碼來源:PeerWirePiece.java

示例6: unlockFile

import java.nio.channels.FileLock; //導入依賴的package包/類
/**
 * Unlock file already locked with {@link #lockFile(String) lockFile()} method
 *
 * @param fileName file name
 */
@Override
public void unlockFile(
                        String fileName ) {

    synchronized (lockedFiles) {

        FileLock fileLock = lockedFiles.get(fileName);
        if (fileLock != null) {
            try {
                fileLock.release();
            } catch (Exception e) {
                throw new FileSystemOperationException("Could not unlock file '" + fileName + "'", e);
            } finally {
                IoUtils.closeStream(fileLock.channel());
                lockedFiles.remove(fileName);
            }
        } else {
            log.warn("File '" + fileName + "' is not locked, so we will not try to unlock it");
        }
    }
}
 
開發者ID:Axway,項目名稱:ats-framework,代碼行數:27,代碼來源:LocalFileSystemOperations.java

示例7: tryLock

import java.nio.channels.FileLock; //導入依賴的package包/類
/**
 * Attempts to acquire an exclusive lock on the directory.
 *
 * @return A lock object representing the newly-acquired lock or
 * <code>null</code> if directory is already locked.
 * @throws IOException if locking fails.
 */
@SuppressWarnings("resource")
private FileLock tryLock(File dir) throws IOException {
  File lockF = new File(dir, FILE_LOCK);
  lockF.deleteOnExit();
  RandomAccessFile file = new RandomAccessFile(lockF, "rws");
  FileLock res = null;
  try {
    res = file.getChannel().tryLock();
  } catch (OverlappingFileLockException oe) {
    file.close();
    return null;
  } catch (IOException e) {
    LOGGER.error("Cannot create lock on " + lockF, e);
    file.close();
    throw e;
  }
  return res;
}
 
開發者ID:moueimei,項目名稱:flume-release-1.7.0,代碼行數:26,代碼來源:Log.java

示例8: unzipFile

import java.nio.channels.FileLock; //導入依賴的package包/類
private File unzipFile(File cachedFile) throws IOException {
  String filename = cachedFile.getName();
  File destDir = new File(cachedFile.getParentFile(), filename + "_unzip");
  if (!destDir.exists()) {
    File lockFile = new File(cachedFile.getParentFile(), filename + "_unzip.lock");
    FileOutputStream out = new FileOutputStream(lockFile);
    try {
      FileLock lock = out.getChannel().lock();
      try {
        // Recheck in case of concurrent processes
        if (!destDir.exists()) {
          Path tempDir = fileCache.createTempDir();
          ZipUtils.unzip(cachedFile, tempDir.toFile(), newLibFilter());
          FileUtils.moveDirectory(tempDir.toFile(), destDir);
        }
      } finally {
        lock.release();
      }
    } finally {
      out.close();
      FileUtils.deleteQuietly(lockFile);
    }
  }
  return destDir;
}
 
開發者ID:instalint-org,項目名稱:instalint,代碼行數:26,代碼來源:DefaultPluginJarExploder.java

示例9: tryWriteLock

import java.nio.channels.FileLock; //導入依賴的package包/類
/**
 * Tries to obtain a write lock on the file. This can be used to verify that no other processes concurrently
 * writes to the file, for example to check that writing to a file, i.e. on a MODIFY_ENTRY event, is completed
 * @param path
 *  the path to the file
 * @return
 *  true, if the lock could be obtained. False, if not. Please not that the lock is released once the method
 *  returns!
 */
public static boolean tryWriteLock(final Path path) {
    try(FileChannel ch = FileChannel.open(path, StandardOpenOption.WRITE);
        FileLock lock = ch.lock()){

        if(lock == null) {
            LOG.log(Level.INFO, "Could not obtain lock on file, maybe still writing");
            return false;
        } else {
            return true;
        }
    } catch (IOException e) {
        LOG.log(Level.INFO, "File not open for write access", e);
        return false;
    }
}
 
開發者ID:gmuecke,項目名稱:boutique-de-jus,代碼行數:25,代碼來源:FileWatcher.java

示例10: fileLock

import java.nio.channels.FileLock; //導入依賴的package包/類
/** write lock file to prevent duplicate execution */
@SuppressWarnings("resource")
public static void fileLock() throws FileNotFoundException {
	lockFile = new File(Main.LOCK_FILE_LOCATION);

	FileChannel channel;
	channel = new RandomAccessFile(lockFile, "rw").getChannel();

	// try lock
	FileLock lock;
	try {
		lock = channel.tryLock();
		// already obtain lock in other JVM
		if (lock == null) {
			channel.close();
			System.exit(0);
		}
	} catch (IOException e) {
		// error handle
	}
}
 
開發者ID:Team-Sprout,項目名稱:Clipcon-Client,代碼行數:22,代碼來源:Main.java

示例11: releaseLock

import java.nio.channels.FileLock; //導入依賴的package包/類
void releaseLock(final FileLock fileLock, final File lockFile) throws IOException {
  if (lockFile == null) {
    return;
  }

  try {
    if (fileLock != null) {
      fileLock.release();
      fileLock.channel().close();
    }
  } finally {
    if (!lockFile.delete()) {
      lockFile.deleteOnExit();
    }
  }
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:17,代碼來源:JarDeployerDUnitTest.java

示例12: ShareFileLockHelper

import java.nio.channels.FileLock; //導入依賴的package包/類
private ShareFileLockHelper(File lockFile) throws IOException {
    this.outputStream = new FileOutputStream(lockFile);
    int numAttempts = 0;
    FileLock localFileLock = null;
    Exception saveException = null;
    while (numAttempts < 3) {
        numAttempts++;
        try {
            localFileLock = this.outputStream.getChannel().lock();
            if (localFileLock != null) {
                break;
            }
            Thread.sleep(10);
        } catch (Exception e) {
            saveException = e;
            Log.e(TAG, "getInfoLock Thread failed time:10");
        }
    }
    if (localFileLock == null) {
        throw new IOException("Tinker Exception:FileLockHelper lock file failed: " + lockFile
                .getAbsolutePath(), saveException);
    }
    this.fileLock = localFileLock;
}
 
開發者ID:JackChan1999,項目名稱:boohee_v5.6,代碼行數:25,代碼來源:ShareFileLockHelper.java

示例13: isPreUpgradableLayout

import java.nio.channels.FileLock; //導入依賴的package包/類
@Override
public boolean isPreUpgradableLayout(StorageDirectory sd) throws IOException {
  File oldF = new File(sd.getRoot(), "storage");
  if (!oldF.exists())
    return false;
  // check the layout version inside the storage file
  // Lock and Read old storage file
  RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws");
  FileLock oldLock = oldFile.getChannel().tryLock();
  try {
    oldFile.seek(0);
    int oldVersion = oldFile.readInt();
    if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION)
      return false;
  } finally {
    oldLock.release();
    oldFile.close();
  }
  return true;
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:21,代碼來源:DataStorage.java

示例14: lock

import java.nio.channels.FileLock; //導入依賴的package包/類
/**
 * Lock storage to provide exclusive access.
 * 
 * <p> Locking is not supported by all file systems.
 * E.g., NFS does not consistently support exclusive locks.
 * 
 * <p> If locking is supported we guarantee exclusive access to the
 * storage directory. Otherwise, no guarantee is given.
 * 
 * @throws IOException if locking fails
 */
public void lock() throws IOException {
  if (isShared()) {
    LOG.info("Locking is disabled for " + this.root);
    return;
  }
  FileLock newLock = tryLock();
  if (newLock == null) {
    String msg = "Cannot lock storage " + this.root 
      + ". The directory is already locked";
    LOG.info(msg);
    throw new IOException(msg);
  }
  // Don't overwrite lock until success - this way if we accidentally
  // call lock twice, the internal state won't be cleared by the second
  // (failed) lock attempt
  lock = newLock;
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:29,代碼來源:Storage.java

示例15: isLockSupported

import java.nio.channels.FileLock; //導入依賴的package包/類
/**
 * Check whether underlying file system supports file locking.
 * 
 * @return <code>true</code> if exclusive locks are supported or
 *         <code>false</code> otherwise.
 * @throws IOException
 * @see StorageDirectory#lock()
 */
public boolean isLockSupported() throws IOException {
  FileLock firstLock = null;
  FileLock secondLock = null;
  try {
    firstLock = lock;
    if(firstLock == null) {
      firstLock = tryLock();
      if(firstLock == null)
        return true;
    }
    secondLock = tryLock();
    if(secondLock == null)
      return true;
  } finally {
    if(firstLock != null && firstLock != lock) {
      firstLock.release();
      firstLock.channel().close();
    }
    if(secondLock != null) {
      secondLock.release();
      secondLock.channel().close();
    }
  }
  return false;
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:34,代碼來源:Storage.java


注:本文中的java.nio.channels.FileLock類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。