Java Code Examples for java.nio.file.OpenOption

The following examples show how to use java.nio.file.OpenOption. These examples are extracted from open source projects. 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 Project: hedera-mirror-node   Source File: NetworkAddressBook.java    License: 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 2
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 3
Source Project: openjdk-jdk9   Source File: ZipFSTester.java    License: 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 Project: coroutines   Source File: AsynchronousFileStep.java    License: 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 5
Source Project: localization_nifi   Source File: MockProcessSession.java    License: 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 Project: cyberduck   Source File: Local.java    License: 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 7
Source Project: openjdk-jdk9   Source File: HttpResponse.java    License: 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 8
Source Project: incubator-tuweni   Source File: Files.java    License: 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 9
Source Project: vividus   Source File: CsvFileCreator.java    License: Apache License 2.0 5 votes vote down vote up
private void createCsvFile(File directory, CsvFileData csvData, boolean append) throws IOException
{
    File file = new File(directory, csvData.getFileName());
    boolean fileExists = file.exists();
    OpenOption[] openOptions = append ? new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.APPEND }
            : new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING };
    try (Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath(), openOptions),
            StandardCharsets.UTF_8);
            CSVPrinter printer = append && fileExists ? csvFormat.print(writer)
                    : csvFormat.withHeader(csvData.getHeader()).print(writer))
    {
        printer.printRecords(csvData.getData());
    }
}
 
Example 10
Source Project: manifold   Source File: PathUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static OutputStream createOutputStream( Path path, OpenOption... options )
{
  try
  {
    return Files.newOutputStream( path, options );
  }
  catch( IOException e )
  {
    throw new RuntimeException( e );
  }
}
 
Example 11
/**
 * 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
/**
 * 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 13
@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
/**
 * 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 15
Source Project: TencentKona-8   Source File: BytesAndLines.java    License: 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
@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 17
/**
 * 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 Project: jdk8u60   Source File: BytesAndLines.java    License: 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 19
Source Project: jdk8u60   Source File: FaultyFileSystem.java    License: 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 20
Source Project: cava   Source File: Files.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Copies the content of a resource to a file.
 *
 * @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(String resourceName, Path destination, OpenOption... options) throws IOException {
  requireNonNull(resourceName);
  requireNonNull(destination);

  try (OutputStream out = java.nio.file.Files.newOutputStream(destination, options)) {
    copyResource(resourceName, out);
  }
  return destination;
}
 
Example 21
Source Project: java-specialagent   Source File: AgentRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run(final RunNotifier notifier) {
  super.run(notifier);
  if (delta != 0)
    return;

  try {
    final String className = getTestClass().getName();
    final File manifestFile = getManifestFile();
    manifestFile.getParentFile().mkdirs();
    final Path path = manifestFile.toPath();
    final OpenOption openOption;
    if (Files.exists(path)) {
      // Check if the test class name is mentioned in the manifest
      try (final BufferedReader reader = new BufferedReader(new FileReader(manifestFile))) {
        String line;
        while ((line = reader.readLine()) != null)
          if (line.equals(className))
            return;
      }

      openOption = StandardOpenOption.APPEND;
    }
    else {
      openOption = StandardOpenOption.CREATE;
    }

    // Add the test class name to the manifest
    Files.write(path, (className + "\n").getBytes(), openOption);
  }
  catch (final IOException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 22
@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 23
Source Project: tessera   Source File: DelegatingFileSystemProviderTest.java    License: 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 24
Source Project: tessera   Source File: DelegatingFileSystemProviderTest.java    License: 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 25
/**
 * 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 26
Source Project: openjdk-jdk8u   Source File: BytesAndLines.java    License: 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 27
@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 28
Source Project: javan-warty-pig   Source File: FilePersistence.java    License: 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 29
Source Project: twister2   Source File: FileUtils.java    License: 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 30
Source Project: jdk8u-jdk   Source File: BytesAndLines.java    License: 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 } ));
}