java.nio.file.OpenOption Java Examples

The following examples show how to use java.nio.file.OpenOption. 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: DataSourceUtil.java    From powsybl-core with Mozilla Public License 2.0 7 votes vote down vote up
static OpenOption[] getOpenOptions(boolean append) {
    OpenOption[] defaultOpenOptions = {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE};
    OpenOption[] appendOpenOptions = {StandardOpenOption.APPEND, StandardOpenOption.WRITE};

    return append ? appendOpenOptions : defaultOpenOptions;
}
 
Example #2
Source File: AsynchronousFileStep.java    From coroutines with Apache License 2.0 6 votes vote down vote up
/***************************************
 * A helper function that opens a file channel for a certain file name and
 * open options.
 *
 * @param  sFileName     The file name
 * @param  rMode         The open option for the file access mode (e.g.
 *                       READ, WRITE)
 * @param  rExtraOptions Optional extra file open options
 *
 * @return The file channel
 */
protected static AsynchronousFileChannel openFileChannel(
	String		  sFileName,
	OpenOption    rMode,
	OpenOption... rExtraOptions)
{
	try
	{
		return AsynchronousFileChannel.open(
			new File(sFileName).toPath(),
			CollectionUtil.join(rExtraOptions, rMode));
	}
	catch (IOException e)
	{
		throw new CoroutineException(e);
	}
}
 
Example #3
Source File: ZipFSTester.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void fchCopy(Path src, Path dst) throws IOException
{
    Set<OpenOption> read = new HashSet<>();
    read.add(READ);
    Set<OpenOption> openwrite = new HashSet<>();
    openwrite.add(CREATE_NEW);
    openwrite.add(WRITE);

    try (FileChannel srcFc = src.getFileSystem()
                                .provider()
                                .newFileChannel(src, read);
         FileChannel dstFc = dst.getFileSystem()
                                .provider()
                                .newFileChannel(dst, openwrite))
    {
        ByteBuffer bb = ByteBuffer.allocate(8192);
        while (srcFc.read(bb) >= 0) {
            bb.flip();
            dstFc.write(bb);
            bb.clear();
        }
    }
}
 
Example #4
Source File: PropertyHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public PropertyHandler(String propertyfile) {
   try {
      this.properties = new Properties();
      this.properties.load(this.getResourceAsStream("/smc.properties"));
      Path configFile = Paths.get(propertyfile);
      if (Files.exists(configFile, new LinkOption[0])) {
         try {
            Charset charset = StandardCharsets.UTF_8;
            String content = new String(Files.readAllBytes(configFile), charset);
            String pathToFile = Paths.get(propertyfile).getParent().toString().replace("\\", "/");
            content = content.replaceAll("%CONF%", pathToFile);
            Files.write(configFile, content.getBytes(charset), new OpenOption[0]);
         } finally {
            this.properties.load(Files.newInputStream(configFile));
         }
      }

      instance = this;
   } catch (Exception var10) {
      throw new RuntimeException(var10);
   }
}
 
Example #5
Source File: MockProcessSession.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void exportTo(final FlowFile flowFile, final Path path, final boolean append) {
    validateState(flowFile);
    if (flowFile == null || path == null) {
        throw new IllegalArgumentException("argument cannot be null");
    }
    if (!(flowFile instanceof MockFlowFile)) {
        throw new IllegalArgumentException("Cannot export a flow file that I did not create");
    }

    final MockFlowFile mock = (MockFlowFile) flowFile;

    final OpenOption mode = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;

    try (final OutputStream out = Files.newOutputStream(path, mode)) {
        out.write(mock.getData());
    } catch (final IOException e) {
        throw new FlowFileAccessException(e.toString(), e);
    }
}
 
Example #6
Source File: NetworkAddressBook.java    From hedera-mirror-node with Apache License 2.0 6 votes vote down vote up
private void saveToDisk(byte[] contents, OpenOption openOption) throws IOException {
    if (contents == null || contents.length == 0) {
        log.warn("Ignored empty byte array");
        return;
    }

    Path path = mirrorProperties.getAddressBookPath();
    Path tempPath = path.resolveSibling(path.getFileName() + ".tmp");
    Files.write(tempPath, contents, StandardOpenOption.CREATE, StandardOpenOption.WRITE, openOption);
    log.info("Saved {}B partial address book update to {}", contents.length, tempPath);

    try {
        Collection<NodeAddress> nodeAddresses = parse(tempPath);
        if (!nodeAddresses.isEmpty()) {
            Files.move(tempPath, path, StandardCopyOption.REPLACE_EXISTING);
            this.nodeAddresses = nodeAddresses;
            log.info("New address book with {} addresses successfully parsed and saved to {}",
                    nodeAddresses.size(), path);
        }
    } catch (Exception e) {
        log.warn("Unable to parse address book: {}", e.getMessage());
    }
}
 
Example #7
Source File: Local.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
protected OutputStream getOutputStream(final String path, final boolean append) throws LocalAccessDeniedException {
    try {
        final Set<OpenOption> options = new HashSet<>();
        options.add(StandardOpenOption.WRITE);
        if(!this.exists()) {
            options.add(StandardOpenOption.CREATE);
        }
        if(append) {
            options.add(StandardOpenOption.APPEND);
        }
        else {
            options.add(StandardOpenOption.TRUNCATE_EXISTING);
        }
        final FileChannel channel = FileChannel.open(Paths.get(path), options);
        return Channels.newOutputStream(channel);
    }
    catch(RuntimeException | IOException e) {
        throw new LocalAccessDeniedException(e.getMessage(), e);
    }
}
 
Example #8
Source File: HttpResponse.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a {@code BodyHandler<Path>} that returns a
 * {@link BodyProcessor BodyProcessor}&lt;{@link Path}&gt;
 * where the download directory is specified, but the filename is
 * obtained from the {@code Content-Disposition} response header. The
 * {@code Content-Disposition} header must specify the <i>attachment</i> type
 * and must also contain a
 * <i>filename</i> parameter. If the filename specifies multiple path
 * components only the final component is used as the filename (with the
 * given directory name). When the {@code HttpResponse} object is
 * returned, the body has been completely written to the file and {@link
 * #body()} returns a {@code Path} object for the file. The returned {@code Path} is the
 * combination of the supplied directory name and the file name supplied
 * by the server. If the destination directory does not exist or cannot
 * be written to, then the response will fail with an {@link IOException}.
 *
 * @param directory the directory to store the file in
 * @param openOptions open options
 * @return a response body handler
 */
public static BodyHandler<Path> asFileDownload(Path directory, OpenOption... openOptions) {
    return (status, headers) -> {
        String dispoHeader = headers.firstValue("Content-Disposition")
                .orElseThrow(() -> unchecked(new IOException("No Content-Disposition")));
        if (!dispoHeader.startsWith("attachment;")) {
            throw unchecked(new IOException("Unknown Content-Disposition type"));
        }
        int n = dispoHeader.indexOf("filename=");
        if (n == -1) {
            throw unchecked(new IOException("Bad Content-Disposition type"));
        }
        int lastsemi = dispoHeader.lastIndexOf(';');
        String disposition;
        if (lastsemi < n) {
            disposition = dispoHeader.substring(n + 9);
        } else {
            disposition = dispoHeader.substring(n + 9, lastsemi);
        }
        Path file = Paths.get(directory.toString(), disposition);
        return BodyProcessor.asFile(file, openOptions);
    };
}
 
Example #9
Source File: BytesAndLines.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Exercise NullPointerException
 */
public void testNulls() {
    Path file = Paths.get("foo");
    byte[] bytes = new byte[100];
    List<String> lines = Collections.emptyList();

    checkNullPointerException(() -> Files.readAllBytes(null));

    checkNullPointerException(() -> Files.write(null, bytes));
    checkNullPointerException(() -> Files.write(file, (byte[])null));
    checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));

    checkNullPointerException(() -> Files.readAllLines(null));
    checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
    checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));

    checkNullPointerException(() -> Files.write(null, lines));
    checkNullPointerException(() -> Files.write(file, (List<String>)null));
    checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
    checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}
 
Example #10
Source File: WindowsChannelFactory.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open/creates file, returning FileChannel to access the file
 *
 * @param   pathForWindows
 *          The path of the file to open/create
 * @param   pathToCheck
 *          The path used for permission checks (if security manager)
 */
static FileChannel newFileChannel(String pathForWindows,
                                  String pathToCheck,
                                  Set<? extends OpenOption> options,
                                  long pSecurityDescriptor)
    throws WindowsException
{
    Flags flags = Flags.toFlags(options);

    // default is reading; append => writing
    if (!flags.read && !flags.write) {
        if (flags.append) {
            flags.write = true;
        } else {
            flags.read = true;
        }
    }

    // validation
    if (flags.read && flags.append)
        throw new IllegalArgumentException("READ + APPEND not allowed");
    if (flags.append && flags.truncateExisting)
        throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");

    FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
    return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
}
 
Example #11
Source File: WindowsChannelFactory.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open/creates file, returning FileChannel to access the file
 *
 * @param   pathForWindows
 *          The path of the file to open/create
 * @param   pathToCheck
 *          The path used for permission checks (if security manager)
 */
static FileChannel newFileChannel(String pathForWindows,
                                  String pathToCheck,
                                  Set<? extends OpenOption> options,
                                  long pSecurityDescriptor)
    throws WindowsException
{
    Flags flags = Flags.toFlags(options);

    // default is reading; append => writing
    if (!flags.read && !flags.write) {
        if (flags.append) {
            flags.write = true;
        } else {
            flags.read = true;
        }
    }

    // validation
    if (flags.read && flags.append)
        throw new IllegalArgumentException("READ + APPEND not allowed");
    if (flags.append && flags.truncateExisting)
        throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");

    FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
    return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
}
 
Example #12
Source File: WindowsChannelFactory.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open/creates file, returning FileChannel to access the file
 *
 * @param   pathForWindows
 *          The path of the file to open/create
 * @param   pathToCheck
 *          The path used for permission checks (if security manager)
 */
static FileChannel newFileChannel(String pathForWindows,
                                  String pathToCheck,
                                  Set<? extends OpenOption> options,
                                  long pSecurityDescriptor)
    throws WindowsException
{
    Flags flags = Flags.toFlags(options);

    // default is reading; append => writing
    if (!flags.read && !flags.write) {
        if (flags.append) {
            flags.write = true;
        } else {
            flags.read = true;
        }
    }

    // validation
    if (flags.read && flags.append)
        throw new IllegalArgumentException("READ + APPEND not allowed");
    if (flags.append && flags.truncateExisting)
        throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");

    FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
    return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
}
 
Example #13
Source File: FaultyFileSystem.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SeekableByteChannel newByteChannel(Path file,
                                          Set<? extends OpenOption> options,
                                          FileAttribute<?>... attrs)
    throws IOException
{
    triggerEx(file, "newByteChannel");
    return Files.newByteChannel(unwrap(file), options, attrs);
}
 
Example #14
Source File: DelegatingFileSystemProviderTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void newFileChannel() throws IOException
{
    final Path path = mock(Path.class);
    final Set<OpenOption> options = new HashSet<>();

    provider.newFileChannel(path, options);

    verify(delegate).newFileChannel(path, options);
}
 
Example #15
Source File: BytesAndLines.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Exercise NullPointerException
 */
public void testNulls() {
    Path file = Paths.get("foo");
    byte[] bytes = new byte[100];
    List<String> lines = Collections.emptyList();

    checkNullPointerException(() -> Files.readAllBytes(null));

    checkNullPointerException(() -> Files.write(null, bytes));
    checkNullPointerException(() -> Files.write(file, (byte[])null));
    checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));

    checkNullPointerException(() -> Files.readAllLines(null));
    checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
    checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));

    checkNullPointerException(() -> Files.write(null, lines));
    checkNullPointerException(() -> Files.write(file, (List<String>)null));
    checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
    checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}
 
Example #16
Source File: DelegatingFileSystemProviderTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void newAsynchronousFileChannel() throws IOException {
    final Path path = mock(Path.class);
    final Set<OpenOption> options = new HashSet<>();
    final ExecutorService executorService = mock(ExecutorService.class);

    provider.newAsynchronousFileChannel(path, options, executorService);

    verify(delegate).newAsynchronousFileChannel(path, options, executorService);
}
 
Example #17
Source File: WindowsChannelFactory.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open/creates file, returning FileChannel to access the file
 *
 * @param   pathForWindows
 *          The path of the file to open/create
 * @param   pathToCheck
 *          The path used for permission checks (if security manager)
 */
static FileChannel newFileChannel(String pathForWindows,
                                  String pathToCheck,
                                  Set<? extends OpenOption> options,
                                  long pSecurityDescriptor)
    throws WindowsException
{
    Flags flags = Flags.toFlags(options);

    // default is reading; append => writing
    if (!flags.read && !flags.write) {
        if (flags.append) {
            flags.write = true;
        } else {
            flags.read = true;
        }
    }

    // validation
    if (flags.read && flags.append)
        throw new IllegalArgumentException("READ + APPEND not allowed");
    if (flags.append && flags.truncateExisting)
        throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");

    FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
    return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
}
 
Example #18
Source File: Files.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Copies the content of a resource to a file.
 *
 * @param classloader The class loader of the resource.
 * @param resourceName The resource name.
 * @param destination The destination file.
 * @param options Options specifying how the destination file should be opened.
 * @return The destination file.
 * @throws IOException If an I/O error occurs.
 */
public static Path copyResource(ClassLoader classloader, String resourceName, Path destination, OpenOption... options)
    throws IOException {
  requireNonNull(resourceName);
  requireNonNull(destination);

  try (OutputStream out = java.nio.file.Files.newOutputStream(destination, options)) {
    copyResource(classloader, resourceName, out);
  }
  return destination;
}
 
Example #19
Source File: BytesAndLines.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Exercise NullPointerException
 */
public void testNulls() {
    Path file = Paths.get("foo");
    byte[] bytes = new byte[100];
    List<String> lines = Collections.emptyList();

    checkNullPointerException(() -> Files.readAllBytes(null));

    checkNullPointerException(() -> Files.write(null, bytes));
    checkNullPointerException(() -> Files.write(file, (byte[])null));
    checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));

    checkNullPointerException(() -> Files.readAllLines(null));
    checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
    checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));

    checkNullPointerException(() -> Files.write(null, lines));
    checkNullPointerException(() -> Files.write(file, (List<String>)null));
    checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
    checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}
 
Example #20
Source File: FaultyFileSystem.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SeekableByteChannel newByteChannel(Path file,
                                          Set<? extends OpenOption> options,
                                          FileAttribute<?>... attrs)
    throws IOException
{
    triggerEx(file, "newByteChannel");
    return Files.newByteChannel(unwrap(file), options, attrs);
}
 
Example #21
Source File: FilePersistence.java    From javan-warty-pig with MIT License 5 votes vote down vote up
/** Helper to read a file into a byte buffer. The buffer is flipped before returned. */
public static ByteBuffer readFile(Path path, OpenOption... options) {
  try (SeekableByteChannel file = Files.newByteChannel(path, options)) {
    ByteBuffer buf = ByteBuffer.allocateDirect((int) file.size());
    file.read(buf);
    if (buf.hasRemaining()) throw new IOException("Failed reading entire file");
    buf.flip();
    return buf;
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example #22
Source File: FileUtils.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public static boolean writeToFile(String filename, byte[] contents, boolean overwrite) {
  // default Files behavior is to overwrite. If we specify no overwrite then CREATE_NEW fails
  // if the file exist. This operation is atomic.
  OpenOption[] options = overwrite
      ? new OpenOption[]{} : new OpenOption[]{StandardOpenOption.CREATE_NEW};

  try {
    Files.write(new File(filename).toPath(), contents, options);
  } catch (IOException e) {
    LOG.log(Level.SEVERE, "Failed to write content to file. ", e);
    return false;
  }

  return true;
}
 
Example #23
Source File: BytesAndLines.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Exercise NullPointerException
 */
public void testNulls() {
    Path file = Paths.get("foo");
    byte[] bytes = new byte[100];
    List<String> lines = Collections.emptyList();

    checkNullPointerException(() -> Files.readAllBytes(null));

    checkNullPointerException(() -> Files.write(null, bytes));
    checkNullPointerException(() -> Files.write(file, (byte[])null));
    checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));

    checkNullPointerException(() -> Files.readAllLines(null));
    checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
    checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));

    checkNullPointerException(() -> Files.write(null, lines));
    checkNullPointerException(() -> Files.write(file, (List<String>)null));
    checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
    checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}
 
Example #24
Source File: WindowsChannelFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open/creates file, returning FileChannel to access the file
 *
 * @param   pathForWindows
 *          The path of the file to open/create
 * @param   pathToCheck
 *          The path used for permission checks (if security manager)
 */
static FileChannel newFileChannel(String pathForWindows,
                                  String pathToCheck,
                                  Set<? extends OpenOption> options,
                                  long pSecurityDescriptor)
    throws WindowsException
{
    Flags flags = Flags.toFlags(options);

    // default is reading; append => writing
    if (!flags.read && !flags.write) {
        if (flags.append) {
            flags.write = true;
        } else {
            flags.read = true;
        }
    }

    // validation
    if (flags.read && flags.append)
        throw new IllegalArgumentException("READ + APPEND not allowed");
    if (flags.append && flags.truncateExisting)
        throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");

    FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
    return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
}
 
Example #25
Source File: BytesAndLines.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Exercise NullPointerException
 */
public void testNulls() {
    Path file = Paths.get("foo");
    byte[] bytes = new byte[100];
    List<String> lines = Collections.emptyList();

    checkNullPointerException(() -> Files.readAllBytes(null));

    checkNullPointerException(() -> Files.write(null, bytes));
    checkNullPointerException(() -> Files.write(file, (byte[])null));
    checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));

    checkNullPointerException(() -> Files.readAllLines(null));
    checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));
    checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));

    checkNullPointerException(() -> Files.write(null, lines));
    checkNullPointerException(() -> Files.write(file, (List<String>)null));
    checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));
    checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));
    checkNullPointerException(() -> Files.write(file, lines, (Charset)null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));
    checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));
}
 
Example #26
Source File: FaultyFileSystem.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SeekableByteChannel newByteChannel(Path file,
                                          Set<? extends OpenOption> options,
                                          FileAttribute<?>... attrs)
    throws IOException
{
    triggerEx(file, "newByteChannel");
    return Files.newByteChannel(unwrap(file), options, attrs);
}
 
Example #27
Source File: LocalWriteFeature.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
    try {
        final java.nio.file.Path p = session.toPath(file);
        final Set<OpenOption> options = new HashSet<>();
        options.add(StandardOpenOption.WRITE);
        if(status.isAppend()) {
            if(!status.isExists()) {
                options.add(StandardOpenOption.CREATE);
            }
        }
        else {
            if(status.isExists()) {
                if(file.isSymbolicLink()) {
                    Files.delete(p);
                    options.add(StandardOpenOption.CREATE);
                }
                else {
                    options.add(StandardOpenOption.TRUNCATE_EXISTING);
                }
            }
            else {
                options.add(StandardOpenOption.CREATE_NEW);
            }
        }
        final FileChannel channel = FileChannel.open(session.toPath(file), options.stream().toArray(OpenOption[]::new));
        channel.position(status.getOffset());
        return new VoidStatusOutputStream(Channels.newOutputStream(channel));
    }
    catch(IOException e) {
        throw new LocalExceptionMappingService().map("Upload {0} failed", e, file);
    }
}
 
Example #28
Source File: FMFileAccessController.java    From BiglyBT with GNU General Public License v2.0 5 votes vote down vote up
public
FileAccessorRAF(
	File			file,
	String			access_mode )

	throws FileNotFoundException
{
	if ( enable_sparse_files && !file.exists()){
		
		try{
			Set<OpenOption>	options = new HashSet<>();
			
			options.add( StandardOpenOption.WRITE );
			options.add( StandardOpenOption.CREATE_NEW );
			options.add( StandardOpenOption.SPARSE );
			
			FileChannel fc = FileChannel.open( file.toPath(), options );
			
			fc.close();
			
		}catch( Throwable e ){
			
		}
	}
	
	raf = new RandomAccessFile( file, access_mode );
}
 
Example #29
Source File: JrtFileSystem.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void checkOptions(Set<? extends OpenOption> options) {
    // check for options of null type and option is an intance of StandardOpenOption
    for (OpenOption option : options) {
        Objects.requireNonNull(option);
        if (!(option instanceof StandardOpenOption)) {
            throw new IllegalArgumentException(
                "option class: " + option.getClass());
        }
    }
    if (options.contains(StandardOpenOption.WRITE) ||
        options.contains(StandardOpenOption.APPEND)) {
        throw readOnly();
    }
}
 
Example #30
Source File: WindowsChannelFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open/creates file, returning FileChannel to access the file
 *
 * @param   pathForWindows
 *          The path of the file to open/create
 * @param   pathToCheck
 *          The path used for permission checks (if security manager)
 */
static FileChannel newFileChannel(String pathForWindows,
                                  String pathToCheck,
                                  Set<? extends OpenOption> options,
                                  long pSecurityDescriptor)
    throws WindowsException
{
    Flags flags = Flags.toFlags(options);

    // default is reading; append => writing
    if (!flags.read && !flags.write) {
        if (flags.append) {
            flags.write = true;
        } else {
            flags.read = true;
        }
    }

    // validation
    if (flags.read && flags.append)
        throw new IllegalArgumentException("READ + APPEND not allowed");
    if (flags.append && flags.truncateExisting)
        throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");

    FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
    return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, null);
}