Here are the examples of the java api class java.nio.channels.AsynchronousFileChannel taken from open source projects.
1. TestVerboseFS#testAsyncFileChannel()
Project: lucene-solr
File: TestVerboseFS.java
File: TestVerboseFS.java
/** Test AsynchronousFileChannel.open */ public void testAsyncFileChannel() throws IOException { InfoStreamListener stream = new InfoStreamListener("newAsynchronousFileChannel"); Path dir = wrap(createTempDir(), stream); AsynchronousFileChannel channel = AsynchronousFileChannel.open(dir.resolve("foobar"), StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE); assertTrue(stream.sawMessage()); channel.close(); try { AsynchronousFileChannel.open(dir.resolve("foobar"), StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE); fail("didn't get expected exception"); } catch (IOException expected) { } }
2. TestLeakFS#testLeakAsyncFileChannel()
Project: lucene-solr
File: TestLeakFS.java
File: TestLeakFS.java
/** Test leaks via AsynchronousFileChannel.open */ public void testLeakAsyncFileChannel() throws IOException { Path dir = wrap(createTempDir()); OutputStream file = Files.newOutputStream(dir.resolve("stillopen")); file.write(5); file.close(); AsynchronousFileChannel leak = AsynchronousFileChannel.open(dir.resolve("stillopen")); try { dir.getFileSystem().close(); fail("should have gotten exception"); } catch (Exception e) { assertTrue(e.getMessage().contains("file handle leaks")); } leak.close(); }
3. HandleTrackingFS#newAsynchronousFileChannel()
Project: lucene-solr
File: HandleTrackingFS.java
File: HandleTrackingFS.java
@Override public AsynchronousFileChannel newAsynchronousFileChannel(Path path, Set<? extends OpenOption> options, ExecutorService executor, FileAttribute<?>... attrs) throws IOException { AsynchronousFileChannel channel = new FilterAsynchronousFileChannel(super.newAsynchronousFileChannel(path, options, executor, attrs)) { boolean closed; @Override public void close() throws IOException { try { if (!closed) { closed = true; onClose(path, this); } } finally { super.close(); } } @Override public String toString() { return "AsynchronousFileChannel(" + path.toString() + ")"; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object obj) { return this == obj; } }; callOpenHook(path, channel); return channel; }
4. FiberFileChannel#open()
Project: quasar
File: FiberFileChannel.java
File: FiberFileChannel.java
/** * Opens or creates a file for reading and/or writing, returning a file channel to access the file. * * <p> * The {@code options} parameter determines how the file is opened. * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE * WRITE} options determines if the file should be opened for reading and/or * writing. If neither option is contained in the array then an existing file * is opened for reading. * * <p> * In addition to {@code READ} and {@code WRITE}, the following options * may be present: * * <table border=1 cellpadding=5 summary=""> * <tr> <th>Option</th> <th>Description</th> </tr> * <tr> * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> * <td> When opening an existing file, the file is first truncated to a * size of 0 bytes. This option is ignored when the file is opened only * for reading.</td> * </tr> * <tr> * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td> * <td> If this option is present then a new file is created, failing if * the file already exists. When creating a file the check for the * existence of the file and the creation of the file if it does not exist * is atomic with respect to other file system operations. This option is * ignored when the file is opened only for reading. </td> * </tr> * <tr> * <td > {@link StandardOpenOption#CREATE CREATE} </td> * <td> If this option is present then an existing file is opened if it * exists, otherwise a new file is created. When creating a file the check * for the existence of the file and the creation of the file if it does * not exist is atomic with respect to other file system operations. This * option is ignored if the {@code CREATE_NEW} option is also present or * the file is opened only for reading. </td> * </tr> * <tr> * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td> * <td> When this option is present then the implementation makes a * <em>best effort</em> attempt to delete the file when closed by the * the {@link #close close} method. If the {@code close} method is not * invoked then a <em>best effort</em> attempt is made to delete the file * when the Java virtual machine terminates. </td> * </tr> * <tr> * <td>{@link StandardOpenOption#SPARSE SPARSE} </td> * <td> When creating a new file this option is a <em>hint</em> that the * new file will be sparse. This option is ignored when not creating * a new file. </td> * </tr> * <tr> * <td> {@link StandardOpenOption#SYNC SYNC} </td> * <td> Requires that every update to the file's content or metadata be * written synchronously to the underlying storage device. (see <a * href="../file/package-summary.html#integrity"> Synchronized I/O file * integrity</a>). </td> * <tr> * <tr> * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> * <td> Requires that every update to the file's content be written * synchronously to the underlying storage device. (see <a * href="../file/package-summary.html#integrity"> Synchronized I/O file * integrity</a>). </td> * </tr> * </table> * * <p> * An implementation may also support additional options. * * <p> * The {@code executor} parameter is the {@link ExecutorService} to * which tasks are submitted to handle I/O events and dispatch completion * results for operations initiated on resulting channel. * The nature of these tasks is highly implementation specific and so care * should be taken when configuring the {@code Executor}. Minimally it * should support an unbounded work queue and should not run tasks on the * caller thread of the {@link ExecutorService#execute execute} method. * Shutting down the executor service while the channel is open results in * unspecified behavior. * * <p> * The {@code attrs} parameter is an optional array of file {@link * FileAttribute file-attributes} to set atomically when creating the file. * * <p> * The new channel is created by invoking the {@link * FileSystemProvider#newFileChannel newFileChannel} method on the * provider that created the {@code Path}. * * @param path The path of the file to open or create * @param options Options specifying how the file is opened * @param ioExecutor The thread pool or {@code null} to associate the channel with the default thread pool * @param attrs An optional list of file attributes to set atomically when creating the file * * @return A new file channel * * @throws IllegalArgumentException If the set contains an invalid combination of options * @throws UnsupportedOperationException If the {@code file} is associated with a provider that does not * support creating asynchronous file channels, or an unsupported * open option is specified, or the array contains an attribute that * cannot be set atomically when creating the file * @throws IOException If an I/O error occurs * @throws SecurityException If a security manager is installed and it denies an * unspecified permission required by the implementation. * In the case of the default provider, the {@link SecurityManager#checkRead(String)} * method is invoked to check read access if the file is opened for reading. * The {@link SecurityManager#checkWrite(String)} method is invoked to check * write access if the file is opened for writing */ @Suspendable public static FiberFileChannel open(final ExecutorService ioExecutor, final Path path, final Set<? extends OpenOption> options, final FileAttribute<?>... attrs) throws IOException { // FiberAsyncIO.ioExecutor(); // final ExecutorService ioExec = ioExecutor != null ? ioExecutor : fiberFileThreadPool; AsynchronousFileChannel afc = FiberAsyncIO.runBlockingIO(fiberFileThreadPool, new CheckedCallable<AsynchronousFileChannel, IOException>() { @Override public AsynchronousFileChannel call() throws IOException { return AsynchronousFileChannel.open(path, options, ioExec, attrs); } }); return new FiberFileChannel(afc); }
5. FileLockConstructor#main()
Project: openjdk
File: FileLockConstructor.java
File: FileLockConstructor.java
public static void main(String[] args) throws IOException { FileLock fileLock = null; int failures = 0; // null FileChannel boolean exceptionThrown = false; try { fileLock = new FileLockSub((FileChannel) null, 0, 0, false); } catch (NullPointerException npe) { exceptionThrown = true; } if (!exceptionThrown) { System.err.println("FileLock constructor did not throw NPE for null FileChannel"); failures++; } // null AsynchronousFileChannel exceptionThrown = false; try { fileLock = new FileLockSub((AsynchronousFileChannel) null, 0, 0, true); } catch (NullPointerException npe) { exceptionThrown = true; } if (!exceptionThrown) { System.err.println("FileLock constructor did not throw NPE for null AsynchronousFileChannel"); failures++; } // create temporary file File tmpFile = File.createTempFile("FileLock", "tmp"); tmpFile.deleteOnExit(); // position and size preconditions long[][] posAndSize = new long[][] { // valid { 0, 42 }, // invalid: position < 0 { -1, 42 }, // invalid: size < 0 { 0, -1 }, // invalid: position + size < 0 { Long.MAX_VALUE, 1 } }; // test position and size preconditions for FileChannel case try (FileChannel syncChannel = FileChannel.open(tmpFile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE)) { for (int i = 0; i < posAndSize.length; i++) { boolean preconditionsHold = i == 0; exceptionThrown = false; try { fileLock = new FileLockSub(syncChannel, posAndSize[i][0], posAndSize[i][1], true); } catch (IllegalArgumentException iae) { exceptionThrown = true; } catch (Exception e) { System.err.println("Unexpected exception \"" + e + "\" caught" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for FileChannel variant"); failures++; continue; } if (preconditionsHold && exceptionThrown) { System.err.println("FileLock constructor incorrectly threw IAE" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for FileChannel variant"); failures++; } else if (!preconditionsHold && !exceptionThrown) { System.err.println("FileLock constructor did not throw IAE" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for FileChannel variant"); failures++; } } } // test position and size preconditions for AsynchronousFileChannel case try (AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(tmpFile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE)) { for (int i = 0; i < posAndSize.length; i++) { boolean preconditionsHold = i == 0; exceptionThrown = false; try { fileLock = new FileLockSub(asyncChannel, posAndSize[i][0], posAndSize[i][1], true); } catch (IllegalArgumentException iae) { exceptionThrown = true; } catch (Exception e) { System.err.println("Unexpected exception \"" + e + "\" caught" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for AsynchronousFileChannel variant"); failures++; continue; } if (preconditionsHold && exceptionThrown) { System.err.println("FileLock constructor incorrectly threw IAE" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for AsynchronousFileChannel variant"); failures++; } else if (!preconditionsHold && !exceptionThrown) { System.err.println("FileLock constructor did not throw IAE" + " for position " + posAndSize[i][0] + " and size " + posAndSize[i][1] + " for AsynchronousFileChannel variant"); failures++; } } } if (failures > 0) { throw new RuntimeException("Incurred " + failures + " failures while testing FileLock."); } }
6. AsyncWrite_OneChanel_Test#main()
Project: live-chat-engine
File: AsyncWrite_OneChanel_Test.java
File: AsyncWrite_OneChanel_Test.java
public static void main(String[] args) throws Exception { Path path = Paths.get("./test-out/nio-test.txt"); File file = path.toFile(); file.delete(); file.createNewFile(); ArrayList<Task> list = new ArrayList<>(); for (int i = 0; i < taskCount; i++) { list.add(new Task(i + 1)); } try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, READ, WRITE)) { for (Task task : list) { task.writeAsync(fileChannel); } } catch (IOException e) { e.printStackTrace(); } //wait end synchronized (endObject) { try { if (endCount != taskCount) endObject.wait(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("end"); }
7. JimfsFileSystemCloseTest#testOpenChannelsClosed()
Project: jimfs
File: JimfsFileSystemCloseTest.java
File: JimfsFileSystemCloseTest.java
@Test public void testOpenChannelsClosed() throws IOException { Path p = fs.getPath("/foo"); FileChannel fc = FileChannel.open(p, READ, WRITE, CREATE); SeekableByteChannel sbc = Files.newByteChannel(p, READ); AsynchronousFileChannel afc = AsynchronousFileChannel.open(p, READ, WRITE); assertTrue(fc.isOpen()); assertTrue(sbc.isOpen()); assertTrue(afc.isOpen()); fs.close(); assertFalse(fc.isOpen()); assertFalse(sbc.isOpen()); assertFalse(afc.isOpen()); try { fc.size(); fail(); } catch (ClosedChannelException expected) { } try { sbc.size(); fail(); } catch (ClosedChannelException expected) { } try { afc.size(); fail(); } catch (ClosedChannelException expected) { } }