Java Code Examples for java.nio.channels.FileChannel#isOpen()

The following examples show how to use java.nio.channels.FileChannel#isOpen() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileMapStorage.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Dispose of a ByteBuffer which has been acquired for writing by one of
 * the write methods, writing its contents to the file.
 */
public int write (ByteBuffer bb) throws IOException {
    synchronized (this) {
        if (bb == buffer) {
            buffer = null;
        }
    }
    int position = size();
    int byteCount = bb.position();
    bb.flip();
    FileChannel channel = writeChannel();
    if (channel.isOpen()) { //If a thread was terminated while writing, it will be closed
        Thread.interrupted(); // #186629: must clear interrupt flag or channel will be broken
        channel.write (bb);
        synchronized (this) {
            bytesWritten += byteCount;
            outstandingBufferCount--;
        }
    }
    return position;
}
 
Example 2
Source File: FileUtils.java    From soundboard with GNU General Public License v3.0 6 votes vote down vote up
public static void copyToInternal(Context context, File file) {
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    String internalPath = getInternalPath(context, file);
    if (internalPath != null) {
        try {
            File outputFile = new File(internalPath);
            inChannel = new FileInputStream(file).getChannel();
            outChannel = new FileOutputStream(outputFile).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            Log.d(LOG_TAG, String.format("Copied %s to %s", file.getAbsolutePath(), outputFile.getAbsolutePath()));
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage());
            try {
                if (inChannel != null && inChannel.isOpen()) {
                    inChannel.close();
                }
                if (outChannel != null && outChannel.isOpen()) {
                    outChannel.close();
                }
            } catch (IOException ignored) {
            }
        }
    }
}
 
Example 3
Source File: FileLockNodeManager.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void stop() throws Exception {
   for (FileChannel channel : lockChannels) {
      if (channel != null && channel.isOpen()) {
         try {
            channel.close();
         } catch (Throwable e) {
            // I do not want to interrupt a shutdown. If anything is wrong here, just log it
            // it could be a critical error or something like that throwing the system down
            logger.warn(e.getMessage(), e);
         }
      }
   }

   super.stop();
}
 
Example 4
Source File: FileIOEngine.java    From hbase with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void refreshFileConnection(int accessFileNum, IOException ioe) throws IOException {
  ReentrantLock channelLock = channelLocks[accessFileNum];
  channelLock.lock();
  try {
    FileChannel fileChannel = fileChannels[accessFileNum];
    if (fileChannel != null) {
      // Don't re-open a channel if we were waiting on another
      // thread to re-open the channel and it is now open.
      if (fileChannel.isOpen()) {
        return;
      }
      fileChannel.close();
    }
    LOG.warn("Caught ClosedChannelException accessing BucketCache, reopening file: "
        + filePaths[accessFileNum], ioe);
    rafs[accessFileNum] = new RandomAccessFile(filePaths[accessFileNum], "rw");
    fileChannels[accessFileNum] = rafs[accessFileNum].getChannel();
  } finally{
    channelLock.unlock();
  }
}
 
Example 5
Source File: FLVReader.java    From red5-io with Apache License 2.0 6 votes vote down vote up
/**
 * Creates FLV reader from file channel.
 *
 * @param channel
 *            file channel
 * @throws IOException
 *             on error
 */
public FLVReader(FileChannel channel) throws IOException {
    if (null == channel) {
        log.warn("Reader was passed a null channel");
        log.debug("{}", org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(this));
    }
    if (!channel.isOpen()) {
        log.warn("Reader was passed a closed channel");
        return;
    }
    this.channel = channel;
    channelSize = channel.size();
    log.debug("Channel size: {}", channelSize);
    if (channel.position() > 0) {
        log.debug("Channel position: {}", channel.position());
        channel.position(0);
    }
    fillBuffer();
    postInitialize();
}
 
Example 6
Source File: X86HttpDownBootstrap.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
@Override
public boolean doFileWriter(ChunkInfo chunkInfo, ByteBuffer buffer) throws IOException {
  Closeable[] fileChannels = getFileWriter(chunkInfo);
  if (fileChannels != null && fileChannels.length > 0) {
    FileChannel fileChannel = (FileChannel) getFileWriter(chunkInfo)[0];
    if (fileChannel != null && fileChannel.isOpen()) {
      fileChannel.write(buffer);
      return true;
    }
  }
  return false;
}
 
Example 7
Source File: AsyncFileLock.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new AsyncFileLock from the given FileChannel.
 * The channel must have been opened with the WRITE option.
 * @param file to lock.
 * @throws IOException I/O error happened.
 */
public AsyncFileLock(FileChannel file) throws IOException
{
   Objects.requireNonNull(file);
   if (!file.isOpen())
   {
      throw new IllegalArgumentException("param `file` is closed");
   }
   fileToLock = file;
   closeChannel = false;
}
 
Example 8
Source File: LargeMessageControllerImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * @throws FileNotFoundException
 */
private FileChannel checkOpen() throws IOException {
   FileChannel channel = cachedChannel;
   if (cachedFile != null || !channel.isOpen()) {
      channel = FileChannel.open(cachedFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
      cachedChannel = channel;
   }
   return channel;
}
 
Example 9
Source File: LargeMessageControllerImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void close() {
   FileChannel cachedChannel = this.cachedChannel;
   if (cachedChannel != null && cachedChannel.isOpen()) {
      this.cachedChannel = null;
      try {
         cachedChannel.close();
      } catch (Exception e) {
         ActiveMQClientLogger.LOGGER.errorClosingCache(e);
      }
   }
}
 
Example 10
Source File: FileMapStorage.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private FileChannel writeChannel() throws IOException {
    FileChannel channel = fileChannel();
    closed = !channel.isOpen();
    return channel;
}
 
Example 11
Source File: FMFileAccessLinear.java    From BiglyBT with GNU General Public License v2.0 4 votes vote down vote up
public void
read(
	FileAccessor		fa,
	DirectByteBuffer	buffer,
	long				offset )

	throws FMFileManagerException
{
	if ( fa == null){

		throw new FMFileManagerException( "read: fa is null" );
	}

	FileChannel fc = fa.getChannel();

	if ( !fc.isOpen()){

		Debug.out("FileChannel is closed: " + owner.getName());

		throw( new FMFileManagerException( "read - file is closed"));
	}

	AEThread2.setDebug( owner );

	try{
		if(USE_MMAP)
		{
			long remainingInFile = fc.size()-offset;
			long remainingInTargetBuffer = buffer.remaining(DirectByteBuffer.SS_FILE);
			MappedByteBuffer buf = fc.map(MapMode.READ_ONLY, offset, Math.min(remainingInFile,remainingInTargetBuffer));
			buffer.put(DirectByteBuffer.SS_FILE, buf);
		} else {
			fc.position(offset);
			while (fc.position() < fc.size() && buffer.hasRemaining(DirectByteBuffer.SS_FILE))
				buffer.read(DirectByteBuffer.SS_FILE,fc);
		}



	}catch ( Exception e ){

		Debug.printStackTrace( e );

		throw( new FMFileManagerException( "read fails", e ));
	}
}
 
Example 12
Source File: FMFileAccessLinear.java    From TorrentEngine with GNU General Public License v3.0 4 votes vote down vote up
public void
read(
	RandomAccessFile	raf,
	DirectByteBuffer	buffer,
	long				offset )

	throws FMFileManagerException
{
	if (raf == null){
		
		throw new FMFileManagerException( "read: raf is null" );
	}
   
	FileChannel fc = raf.getChannel();
   		
	if ( !fc.isOpen()){
		
		Debug.out("FileChannel is closed: " + owner.getName());
		
		throw( new FMFileManagerException( "read - file is closed"));
	}

	AEThread2.setDebug( owner );
	
	try{
		if(USE_MMAP)
		{
			long remainingInFile = fc.size()-offset;
			long remainingInTargetBuffer = buffer.remaining(DirectByteBuffer.SS_FILE);
			MappedByteBuffer buf = fc.map(MapMode.READ_ONLY, offset, Math.min(remainingInFile,remainingInTargetBuffer));
			buffer.put(DirectByteBuffer.SS_FILE, buf);
		} else {
			fc.position(offset);
			while (fc.position() < fc.size() && buffer.hasRemaining(DirectByteBuffer.SS_FILE))
				buffer.read(DirectByteBuffer.SS_FILE,fc);				
		}

		
		
	}catch ( Exception e ){
		
		Debug.printStackTrace( e );
		
		throw( new FMFileManagerException( "read fails", e ));
	}
}