### Question:
NativeIO { public static native FileDescriptor open(String path, int flags, int mode) throws IOException;  static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native Stat fstat(FileDescriptor fd); static native void chmod(String path, int mode); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; }### Answer:
@Test public void testOpenMissingWithoutCreate() throws Exception { LOG.info("Open a missing file without O_CREAT and it should fail"); try { FileDescriptor fd = NativeIO.open( new File(TEST_DIR, "doesntexist").getAbsolutePath(), NativeIO.O_WRONLY, 0700); fail("Able to open a new file without O_CREAT"); } catch (NativeIOException nioe) { LOG.info("Got expected exception", nioe); assertEquals(Errno.ENOENT, nioe.getErrno()); } }
@Test public void testOpenWithCreate() throws Exception { LOG.info("Test creating a file with O_CREAT"); FileDescriptor fd = NativeIO.open( new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(), NativeIO.O_WRONLY | NativeIO.O_CREAT, 0700); assertNotNull(true); assertTrue(fd.valid()); FileOutputStream fos = new FileOutputStream(fd); fos.write("foo".getBytes()); fos.close(); assertFalse(fd.valid()); LOG.info("Test exclusive create"); try { fd = NativeIO.open( new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(), NativeIO.O_WRONLY | NativeIO.O_CREAT | NativeIO.O_EXCL, 0700); fail("Was able to create existing file with O_EXCL"); } catch (NativeIOException nioe) { LOG.info("Got expected exception for failed exclusive create", nioe); assertEquals(Errno.EEXIST, nioe.getErrno()); } }
@Test public void testFDDoesntLeak() throws IOException { for (int i = 0; i < 10000; i++) { FileDescriptor fd = NativeIO.open( new File(TEST_DIR, "testNoFdLeak").getAbsolutePath(), NativeIO.O_WRONLY | NativeIO.O_CREAT, 0700); assertNotNull(true); assertTrue(fd.valid()); FileOutputStream fos = new FileOutputStream(fd); fos.write("foo".getBytes()); fos.close(); } }