本文整理汇总了Java中java.nio.channels.FileChannel类的典型用法代码示例。如果您正苦于以下问题:Java FileChannel类的具体用法?Java FileChannel怎么用?Java FileChannel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
FileChannel类属于java.nio.channels包,在下文中一共展示了FileChannel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: openReader
import java.nio.channels.FileChannel; //导入依赖的package包/类
private FileChannel openReader(long generationId) throws IOException {
ensureOpen();
if (readChannels.containsKey(generationId)) {
return readChannels.get(generationId);
}
try {
Path translogFilePath = this.translogPath.resolve(getFileNameFromId(tmpTranslogGeneration.get()));
if (!Files.exists(translogFilePath)) {
return null;
}
// maybe a lot of readers try to open reader and put it to readChannel cache, because read lock is shared
FileChannel readChannel = FileChannel.open(translogFilePath, StandardOpenOption.READ);
FileChannel originReadChannel = readChannels.putIfAbsent(generationId, readChannel);
if (originReadChannel != null) {
IOUtils.close(readChannel);
return originReadChannel;
} else {
return readChannel;
}
} catch (Throwable e) {
throw e;
}
}
示例2: truncateFileAtURL
import java.nio.channels.FileChannel; //导入依赖的package包/类
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
File file = new File(filesystemPathForURL(inputURL));
if (!file.exists()) {
throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
}
RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
try {
if (raf.length() >= size) {
FileChannel channel = raf.getChannel();
channel.truncate(size);
return size;
}
return raf.length();
} finally {
raf.close();
}
}
示例3: isId3Tag
import java.nio.channels.FileChannel; //导入依赖的package包/类
/**
* Is ID3 tag
*
* @param fc
* @return
* @throws IOException
*/
public static boolean isId3Tag(FileChannel fc) throws IOException
{
if (!isID3V2Header(fc))
{
return false;
}
//So we have a tag
ByteBuffer bb = ByteBuffer.allocateDirect(FIELD_TAG_SIZE_LENGTH);
fc.position(fc.position() + FIELD_TAGID_LENGTH + FIELD_TAG_MAJOR_VERSION_LENGTH + FIELD_TAG_MINOR_VERSION_LENGTH + FIELD_TAG_FLAG_LENGTH);
fc.read(bb);
bb.flip();
int size = ID3SyncSafeInteger.bufferToValue(bb);
fc.position(size + TAG_HEADER_LENGTH);
return true;
}
示例4: writeFileFromBytesByChannel
import java.nio.channels.FileChannel; //导入依赖的package包/类
/**
* 将字节数组写入文件
*
* @param file 文件
* @param bytes 字节数组
* @param append 是否追加在文件末
* @param isForce 是否写入文件
* @return {@code true}: 写入成功<br>{@code false}: 写入失败
*/
public static boolean writeFileFromBytesByChannel(final File file, final byte[] bytes, final boolean append, final boolean isForce) {
if (bytes == null) return false;
FileChannel fc = null;
try {
fc = new FileOutputStream(file, append).getChannel();
fc.position(fc.size());
fc.write(ByteBuffer.wrap(bytes));
if (isForce) fc.force(true);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
CloseUtils.closeIO(fc);
}
}
示例5: writeFileFromBytesByMap
import java.nio.channels.FileChannel; //导入依赖的package包/类
/**
* 将字节数组写入文件
*
* @param file 文件
* @param bytes 字节数组
* @param append 是否追加在文件末
* @param isForce 是否写入文件
* @return {@code true}: 写入成功<br>{@code false}: 写入失败
*/
public static boolean writeFileFromBytesByMap(final File file, final byte[] bytes, final boolean append, final boolean isForce) {
if (bytes == null || !createOrExistsFile(file)) return false;
FileChannel fc = null;
try {
fc = new FileOutputStream(file, append).getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, fc.size(), bytes.length);
mbb.put(bytes);
if (isForce) mbb.force();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
CloseUtils.closeIO(fc);
}
}
示例6: waitForMuxing
import java.nio.channels.FileChannel; //导入依赖的package包/类
/**
* At this point, we are still muxing, and trying to read beyond muxed data.
*
* We park here and wait until it is available.
*/
private int waitForMuxing(Muxer muxer, long maxPosition, FileChannel fileChannel, int fileHandle, MuxedFile muxedFile)
throws IOException, InterruptedException {
long currentSize = 0;
while (maxPosition >= (currentSize = fileChannel.size())) {
State state = muxer.state();
switch (state) {
case RUNNING:
logger.debug("Want to read @ {} (file is {}), so waiting for {}", maxPosition, currentSize, muxer);
sleeper.sleep(MUX_WAIT_LOOP_MS);
break;
case SUCCESSFUL:
logger.debug("Done waiting to read @ {}", maxPosition, muxer);
return SUCCESS;
case FAILED:
return muxingFailed(fileHandle, muxedFile, muxer);
default:
logger.error("BUG: Unhandled state {} in muxer {}", state, muxer);
return BUG;
}
}
logger.debug("Done waiting to read @ {}", maxPosition, muxer);
return SUCCESS;
}
示例7: shouldReleaseTaskStateDirectoryLock
import java.nio.channels.FileChannel; //导入依赖的package包/类
@Test
public void shouldReleaseTaskStateDirectoryLock() throws Exception {
final TaskId taskId = new TaskId(0, 0);
final File taskDirectory = directory.directoryForTask(taskId);
directory.lock(taskId, 1);
directory.unlock(taskId);
try (
final FileChannel channel = FileChannel.open(
new File(taskDirectory, StateDirectory.LOCK_FILE_NAME).toPath(),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE)
) {
channel.tryLock();
}
}
示例8: delete
import java.nio.channels.FileChannel; //导入依赖的package包/类
/**
* Delete Tag
*
* @param file to delete the tag from
* @throws IOException if problem accessing the file
* <p/>
*/
//TODO should clear all data and preferably recover lost space and go upto end of mp3s
public void delete(RandomAccessFile file) throws IOException {
// this works by just erasing the "ID3" tag at the beginning
// of the file
byte[] buffer = new byte[FIELD_TAGID_LENGTH];
//Read into Byte Buffer
final FileChannel fc = file.getChannel();
fc.position();
ByteBuffer byteBuffer = ByteBuffer.allocate(TAG_HEADER_LENGTH);
fc.read(byteBuffer, 0);
byteBuffer.flip();
if (seek(byteBuffer)) {
file.seek(0L);
file.write(buffer);
}
}
示例9: readFile2BytesByMap
import java.nio.channels.FileChannel; //导入依赖的package包/类
/**
* 读取文件到字节数组中
*
* @param file 文件
* @return 字符数组
*/
public static byte[] readFile2BytesByMap(final File file) {
if (!isFileExists(file)) return null;
FileChannel fc = null;
try {
fc = new RandomAccessFile(file, "r").getChannel();
int size = (int) fc.size();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
byte[] result = new byte[size];
mbb.get(result, 0, size);
return result;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
CloseUtils.closeIO(fc);
}
}
示例10: testUnreadableChannel
import java.nio.channels.FileChannel; //导入依赖的package包/类
private static void testUnreadableChannel() throws Exception {
File blah = File.createTempFile("blah2", null);
blah.deleteOnExit();
FileOutputStream fos = new FileOutputStream(blah);
try {
fos.write(new byte[128]);
FileChannel fc = fos.getChannel();
try {
fc.read(ByteBuffer.allocate(256),1);
throw new RuntimeException("Expected exception not thrown");
} catch(NonReadableChannelException e) {
// Correct result
}
} finally {
fos.close();
blah.delete();
}
}
示例11: LockExclusive
import java.nio.channels.FileChannel; //导入依赖的package包/类
public boolean LockExclusive(File targetFile) {
if (targetFile == null) {
return false;
}
try {
File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
if (!lockFile.exists()) {
lockFile.createNewFile();
}
RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile.getAbsolutePath(), "rw");
FileChannel channel = randomAccessFile.getChannel();
java.nio.channels.FileLock lock = channel.lock();
if (!lock.isValid()) {
return false;
}
RefCntInc(lockFile.getAbsolutePath(), lock, randomAccessFile, channel);
return true;
} catch (Exception e) {
return false;
}
}
示例12: position
import java.nio.channels.FileChannel; //导入依赖的package包/类
public FileChannel position(long newPosition) throws IOException {
ensureOpen();
if (newPosition < 0)
throw new IllegalArgumentException();
synchronized (positionLock) {
long p = -1;
int ti = -1;
try {
begin();
ti = threads.add();
if (!isOpen())
return null;
do {
p = position0(fd, newPosition);
} while ((p == IOStatus.INTERRUPTED) && isOpen());
return this;
} finally {
threads.remove(ti);
end(p > -1);
assert IOStatus.check(p);
}
}
}
示例13: writeNewMetadataLargerButCanUseFreeAtom
import java.nio.channels.FileChannel; //导入依赖的package包/类
/**
* We can fit the metadata in under the meta item just by using some of the padding available in the {@code free}
* atom under the {@code meta} atom need to take of the side of free header otherwise might end up with
* solution where can fit in data, but can't fit in free atom header.
*
* @param fileReadChannel
* @param fileWriteChannel
* @param neroTagsHeader
* @param sizeOfExistingMetaLevelFreeAtom
* @param newIlstData
* @param additionalSpaceRequiredForMetadata
* @throws IOException
* @throws CannotWriteException
*/
private void writeNewMetadataLargerButCanUseFreeAtom(FileChannel fileReadChannel, FileChannel fileWriteChannel, Mp4BoxHeader ilstHeader, Mp4BoxHeader neroTagsHeader, int sizeOfExistingMetaLevelFreeAtom, ByteBuffer newIlstData, int additionalSpaceRequiredForMetadata) throws IOException, CannotWriteException
{
int newFreeSize = sizeOfExistingMetaLevelFreeAtom - (additionalSpaceRequiredForMetadata);
logger.config("Writing:Option 5;Larger Size can use meta free atom need extra:" + newFreeSize + "bytes");
writeDataUptoIncludingIlst(fileReadChannel, fileWriteChannel, ilstHeader, newIlstData);
//Create an amended smaller freeBaos atom and write it to file
Mp4FreeBox newFreeBox = new Mp4FreeBox(newFreeSize - Mp4BoxHeader.HEADER_LENGTH);
fileWriteChannel.write(newFreeBox.getHeader().getHeaderData());
fileWriteChannel.write(newFreeBox.getData());
//Skip over the read channel old free atom
fileReadChannel.position(fileReadChannel.position() + sizeOfExistingMetaLevelFreeAtom);
writeDataAfterIlst(fileReadChannel, fileWriteChannel, neroTagsHeader);
}
示例14: main
import java.nio.channels.FileChannel; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
try (RandomAccessFile aFile = new RandomAccessFile("data/data.txt", "rw")) {
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
System.out.println("Read " + bytesRead);
buf.flip();
while (buf.hasRemaining()) {
System.out.print((char) buf.get());
}
System.out.print("\n");
buf.clear();
bytesRead = inChannel.read(buf);
}
}
}
示例15: releaseFile
import java.nio.channels.FileChannel; //导入依赖的package包/类
private static void releaseFile(final FileChannel channel) {
final File file = file2Channel.reversedGet(channel);
if (file == null) return;
synchronized (file) {
Integer count = channel2ClientsCount.get(channel);
if (count == null) return;//already removed
if (count > 1) {
channel2ClientsCount.put(channel, --count);
} else {
channel2ClientsCount.remove(channel);
file2Channel.reversedRemove(channel);
try {
channel.close();
} catch (IOException ex) {
LogManager.log("can't close channel", ex);
}
}
}
}