本文整理匯總了Java中java.nio.channels.AsynchronousFileChannel類的典型用法代碼示例。如果您正苦於以下問題:Java AsynchronousFileChannel類的具體用法?Java AsynchronousFileChannel怎麽用?Java AsynchronousFileChannel使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
AsynchronousFileChannel類屬於java.nio.channels包,在下文中一共展示了AsynchronousFileChannel類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: followFile
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
public void followFile(Path file, FileInput.InitialReadPosition customInitialReadPosition) throws IOException {
synchronized (this) {
if (isFollowingFile(file)) {
log.debug("Not following file {} because it's already followed.", file);
return;
}
log.debug("Following file {}", file);
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
final ChunkReader chunkReader = new ChunkReader(input, file, fileChannel, chunkQueue, readerBufferSize, customInitialReadPosition, this);
final ScheduledFuture<?> chunkReaderFuture = scheduler.scheduleAtFixedRate(chunkReader, 0, readerInterval, TimeUnit.MILLISECONDS);
chunkReaderTasks.putIfAbsent(file, new ChunkReaderTask(chunkReaderFuture, fileChannel));
}
}
示例2: DocumentBlockFileWriter
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
/**
* Primary constructor
* @param output output file
* @throws IOException Thrown if there is an I/O error when creating file.
*/
public DocumentBlockFileWriter(File output, DocumentStorageLevel level, DataFilter filter) throws IOException {
this.output = output;
this.storageLevel = level;
this.filter = filter;
this.fileChannel = AsynchronousFileChannel.open(Paths.get(output.toURI()), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
try {
byte[] magicHeader = MAGIC_V1;
byte[] filterHeader = filter != null ? filter.id() : DocumentFileWriter.FILTER_NA;
fileChannel.write(ByteBuffer.wrap(magicHeader),0).get();
fileChannel.write(ByteBuffer.wrap(filterHeader),4).get();
allocatedSpace.addAndGet(magicHeader.length+filterHeader.length);
} catch (ExecutionException | InterruptedException e) {
throw new IOException(e);
}
}
示例3: DocumentFileWriter
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
/**
* Primary constructor
* @param output output file
* @throws IOException Thrown if there is an I/O error when creating file.
*/
public DocumentFileWriter(File output, DocumentStorageLevel level, DataFilter filter) throws IOException {
this.output = output;
this.storageLevel = level;
this.filter = filter;
this.fileChannel = AsynchronousFileChannel.open(Paths.get(output.getAbsoluteFile().toURI()), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
try {
fileChannel.write(ByteBuffer.wrap(MAGIC_V1), 0).get();
fileChannel.write(ByteBuffer.wrap(filter == null ? FILTER_NA : filter.id()), 4).get();
allocatedSpace.addAndGet(MAGIC_V1.length + 2);
} catch (ExecutionException | InterruptedException e) {
throw new IOException(e);
}
}
示例4: save
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
private void save(boolean saveLaterIfWriting) {
boolean canSaveNow = currentlyWriting.compareAndSet(false,
true);// atomically sets to true if false
if (canSaveNow) {// no writing is in progress: start one immediately
// Writes the config data to a ByteBuffer
CharsWrapper.Builder builder = new CharsWrapper.Builder(512);
writer.write(config, builder);
CharBuffer chars = CharBuffer.wrap(builder.build());
ByteBuffer buffer = charset.encode(chars);
// Writes the ByteBuffer to the file, asynchronously
synchronized (channelGuard) {
try {
channel = AsynchronousFileChannel.open(file.toPath(), openOptions);
channel.write(buffer, channel.size(), null, writeCompletedHandler);
} catch (IOException e) {
writeCompletedHandler.failed(e, null);
}
}
} else if (saveLaterIfWriting) {// there is a writing in progress: start one later
mustWriteAgain.set(true);
}
}
示例5: tryLock
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
public FileLock tryLock(Channel channel, long start, long size, boolean shared) throws IOException{
if(!channel.isOpen()) {
throw new ClosedChannelException();
}
Iterator<EphemeralFsFileLock> iter = locks.iterator();
while(iter.hasNext()) {
EphemeralFsFileLock oldLock = iter.next();
if(!oldLock.isValid()) {
iter.remove();
}
else if(oldLock.overlaps(start, size)) {
throw new OverlappingFileLockException();
}
}
EphemeralFsFileLock newLock =
channel instanceof FileChannel ?
new EphemeralFsFileLock((FileChannel) channel, start, size, shared) :
new EphemeralFsFileLock((AsynchronousFileChannel) channel, start, size, shared);
locks.add(newLock);
return newLock;
}
示例6: testFutureAsyncReadWrite
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
@Test
public void testFutureAsyncReadWrite() throws Exception {
Path test = root.resolve("test");
try (AsynchronousFileChannel file = AsynchronousFileChannel.open(test,
StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE,
StandardOpenOption.READ
)) {
byte[] contents = new byte[512];
random.nextBytes(contents);
Future<Integer> wf = file.write(ByteBuffer.wrap(contents), 0);
assertEquals((Integer) 512, wf.get());
ByteBuffer read = ByteBuffer.allocate(512);
Future<Integer> rf = file.read(read, 0);
assertEquals((Integer) 512, rf.get());
assertArrayEquals(contents, read.array());
}
}
示例7: testErrorGoesToHandler
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
@Test
public void testErrorGoesToHandler() throws Exception {
Path test = root.resolve("test");
AsynchronousFileChannel file = AsynchronousFileChannel.open(test,
StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE,
StandardOpenOption.READ
);
file.close();
byte[] contents = new byte[512];
random.nextBytes(contents);
CountdownCompletionHandler<Integer> writeCompletionHandler =
new CountdownCompletionHandler<>();
file.write(ByteBuffer.wrap(contents), 0, writeCompletionHandler, writeCompletionHandler);
assertTrue(writeCompletionHandler.getExc() instanceof ClosedChannelException);
}
示例8: main
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
AsynchronousFileChannel afc = AsynchronousFileChannel.open(Paths.get("/Users/life/lifey40Video.avi"), StandardOpenOption.READ) ;
System.out.println(afc.getClass());
ByteBuffer r = ByteBuffer.allocate(500*1024*1024) ;
CompletableFuture<Integer> cf = new CompletableFuture<>();
// sleep(20000);
System.out.println("Now");
long s = System.currentTimeMillis();
Future<Integer> c = afc.read(r,0);
// Future<Integer> a = afc.read(r,10*1024*1024);
CompletableFuture<Integer> cf2 = cf.thenApplyAsync((res) -> {
sleep(1000);
System.out.println("mush");
return res;
}, ForkJoinPool.commonPool());
System.out.println("mish"+cf2.get());
// int i = a.get();
sleep(1000000);
}
示例9: handleStoreFile
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
private void handleStoreFile(GetFileReceiver msg) {
Path file = msg.getFile();
log.debug("storing data in file: {}", file);
ActorRef sender = getSender();
resolveFile(msg, file, false, resolvedFile -> {
try {
ActorRef receiver = getContext().actorOf(
ChannelReceiver.props(AsynchronousFileChannel.open(
resolvedFile,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.CREATE)),
nameGenerator.getName(ChannelReceiver.class));
getSender().tell(new FileReceiver(receiver), getSelf());
} catch(Exception e) {
sender.tell(new Failure(e), getSelf());
}
});
}
示例10: handleFetchFile
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
private void handleFetchFile(FetchFile msg) throws Exception {
Path file = msg.getFile();
log.debug("fetching file: {}", file);
ActorRef sender = getSender();
resolveFile(msg, file, resolvedFile -> {
try {
ActorRef cursor = getContext().actorOf(
ChannelCursor.props(AsynchronousFileChannel.open(
resolvedFile,
StandardOpenOption.READ)),
nameGenerator.getName(ChannelCursor.class));
cursor.tell(new NextItem(), sender);
} catch(Exception e) {
sender.tell(new Failure(e), getSelf());
}
});
}
示例11: writeAsync
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
/**
* Write async.
*
* @param target the target
* @param bytes the bytes
* @param openOptions the open options
* @return the future
*/
public static Future<Void> writeAsync(final Path target,
final byte[] bytes,
final OpenOption... openOptions) {
if (isTraceEnabled)
log.trace("비동기 방식으로 데이터를 파일에 씁니다. target=[{}], openOptions=[{}]", target, listToString(openOptions));
return AsyncTool.startNew(new Callable<Void>() {
@Override
public Void call() throws Exception {
try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(target, openOptions)) {
Future<Integer> result = fileChannel.write(ByteBuffer.wrap(bytes), 0);
while (!result.isDone()) {
Thread.sleep(1);
}
return null;
} catch (Exception e) {
log.error("비동기 방식으로 파일에 쓰는 동안 예외가 발생했습니다.", e);
throw new RuntimeException(e);
}
}
});
}
示例12: ChunkReader
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
public ChunkReader(Input fileInput,
Path path,
AsynchronousFileChannel fileChannel,
BlockingQueue<FileChunk> chunks,
int initialChunkSize,
FileInput.InitialReadPosition initialReadPosition,
ChunkReaderScheduler chunkReaderScheduler) {
this.fileInput = fileInput;
this.path = path;
this.fileChannel = fileChannel;
this.chunks = chunks;
this.initialChunkSize = initialChunkSize;
this.chunkReaderScheduler = chunkReaderScheduler;
Preconditions.checkArgument(initialChunkSize > 0, "Chunk size must be positive");
if (fileChannel.isOpen()) {
try {
final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
fileKey = attr.fileKey();
if (initialReadPosition == FileInput.InitialReadPosition.END) {
position = attr.size();
}
} catch (IOException e) {
log.error("Cannot access file metadata", e);
}
}
}
示例13: readPositionEnd
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
@Test
public void readPositionEnd() throws IOException, InterruptedException {
final Utils.LogFile logFile = new Utils.LogFile(100 * 1024, 400, 100);
logFile.close();
final ArrayBlockingQueue<FileChunk> chunkQueue = Queues.newArrayBlockingQueue(1);
final AsynchronousFileChannel channel = AsynchronousFileChannel.open(logFile.getPath(), StandardOpenOption.READ);
final CountingAsyncFileChannel spy = new CountingAsyncFileChannel(channel);
final ChunkReader chunkReader = new ChunkReader(mock(FileInput.class), logFile.getPath(), spy, chunkQueue, 10 * 1024,
FileInput.InitialReadPosition.END, null);
final ScheduledExecutorService chunkReaderExecutor = Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder()
.setDaemon(false)
.setNameFormat("file-chunk-reader-%d")
.setUncaughtExceptionHandler(this)
.build()
);
final Thread consumer = new Thread() {
@Override
public void run() {
try {
final FileChunk chunk = chunkQueue.poll(2, TimeUnit.SECONDS);
assertNull("Reading from the end of the file must not produce a chunk for a non-changing file.", chunk);
} catch (InterruptedException ignore) {
}
}
};
consumer.start();
chunkReaderExecutor.scheduleAtFixedRate(chunkReader, 0, 250, TimeUnit.MILLISECONDS);
consumer.join();
// we can process one chunk at a time, so one read is queued, the second is buffered
assertEquals("The e should be empty", 1, chunkQueue.remainingCapacity());
}
示例14: save
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
public Publisher<Integer> save(Publisher<Customer> customers) throws IOException {
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
AtomicLong offset = new AtomicLong(0);
AtomicInteger resultCount = new AtomicInteger(0);
SingleItemPublisher<Integer> resultPublisher = new SingleItemPublisher<>();
Semaphore writeSemaphore = new Semaphore(1);
writeSemaphore.acquireUninterruptibly();
fileChannel.write(ByteBuffer.wrap("[".getBytes()), 0, resultPublisher,
andThen((count, s) -> {
writeSemaphore.release();
customers.subscribe(pullEach((Customer customer, Subscription subscription) -> {
String json = String.format("%s{\"firstName\": \"%s\", \"lastName\": \"%s\"}", offset.longValue() == 0 ? "" : ",",
customer.getFirstName(), customer.getLastName());
offset.addAndGet(count);
writeSemaphore.acquireUninterruptibly();
fileChannel.write(ByteBuffer.wrap(json.getBytes()), offset.get(), resultPublisher,
andThen((size, c) -> {
writeSemaphore.release();
offset.addAndGet(size);
resultCount.incrementAndGet();
subscription.request(1);
}));
}).andThen(() -> {
writeSemaphore.acquireUninterruptibly();
fileChannel.write(ByteBuffer.wrap("]".getBytes()), offset.longValue(), resultPublisher,
andThen((d, e) -> {
writeSemaphore.release();
try {
fileChannel.close();
resultPublisher.publish(resultCount.intValue());
} catch (IOException error) {
resultPublisher.publish(error);
}
}));
}).exceptionally(error -> resultPublisher.publish(error)));
}));
return resultPublisher;
}
示例15: openInputChannel
import java.nio.channels.AsynchronousFileChannel; //導入依賴的package包/類
private static AsynchronousFileChannel openInputChannel(File file) {
try {
final Path path = Paths.get(file.getAbsolutePath());
if (!Files.exists(path)) {
Files.createFile(path);
}
return AsynchronousFileChannel.open(path, StandardOpenOption.READ);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}