Java Code Examples for java.nio.file.StandardOpenOption#WRITE

The following examples show how to use java.nio.file.StandardOpenOption#WRITE . 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: MemFileChannel.java    From jackcess with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new MemFileChannel containing the contents of the
 * given Path with the given mode (for mode details see
 * {@link RandomAccessFile#RandomAccessFile(File,String)}).  Note,
 * modifications to the returned channel will <i>not</i> affect the original
 * File source.
 */
public static MemFileChannel newChannel(Path file, OpenOption... opts)
  throws IOException
{
  FileChannel in = null;
  try {
    String mode = RO_CHANNEL_MODE;
    if(opts != null) {
      for(OpenOption opt : opts) {
        if(opt == StandardOpenOption.WRITE) {
          mode = RW_CHANNEL_MODE;
          break;
        }
      }
    }
    return newChannel(in = FileChannel.open(file, StandardOpenOption.READ),
                      mode);
  } finally {
    ByteUtil.closeQuietly(in);
  }
}
 
Example 3
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewOutputStreamExistingSFTPFailure() throws IOException {
    addDirectory("/foo");
    Path bar = addFile("/foo/bar");
    bar.toFile().setReadOnly();

    // failure: no permission to write

    OpenOption[] options = { StandardOpenOption.WRITE };
    FileSystemException exception = assertThrows(FileSystemException.class, () -> fileSystem.newOutputStream(createPath("/foo/bar"), options));
    assertEquals("/foo/bar", exception.getFile());

    verify(getExceptionFactory()).createNewOutputStreamException(eq("/foo/bar"), any(SftpException.class), anyCollection());
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/foo/bar")));
}
 
Example 4
Source File: HardwareStorageUtils.java    From WarpPI with Apache License 2.0 6 votes vote down vote up
@Override
public void write(final File f, final byte[] bytes, final int... options) throws IOException {
	final StandardOpenOption[] noptions = new StandardOpenOption[options.length];
	int i = 0;
	for (final int opt : options) {
		switch (opt) {
			case StorageUtils.OpenOptionCreate: {
				noptions[i] = StandardOpenOption.CREATE;
				break;
			}
			case StorageUtils.OpenOptionWrite: {
				noptions[i] = StandardOpenOption.WRITE;
				break;
			}
			default: {
				break;
			}
		}
		i++;
	}
	Files.write(f.toPath(), bytes, noptions);
}
 
Example 5
Source File: DesktopStorageUtils.java    From WarpPI with Apache License 2.0 6 votes vote down vote up
@Override
public void write(final File f, final byte[] bytes, final int... options) throws IOException {
	final StandardOpenOption[] noptions = new StandardOpenOption[options.length];
	int i = 0;
	for (final int opt : options) {
		switch (opt) {
			case StorageUtils.OpenOptionCreate: {
				noptions[i] = StandardOpenOption.CREATE;
				break;
			}
			case StorageUtils.OpenOptionWrite: {
				noptions[i] = StandardOpenOption.WRITE;
				break;
			}
			default: {
				break;
			}
		}
		i++;
	}
	Files.write(f.toPath(), bytes, noptions);
}
 
Example 6
Source File: OpenOptions.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
static OpenOptions forNewOutputStream(Collection<? extends OpenOption> options) {
    if (options.isEmpty()) {
        // CREATE, TRUNCATE_EXISTING and WRITE, i.e. create, not createNew, and not append
        return new OpenOptions(false, true, false, true, false, false, Collections.<OpenOption>emptySet());
    }

    boolean append = false;
    boolean truncateExisting = false;
    boolean create = false;
    boolean createNew = false;
    boolean deleteOnClose = false;

    for (OpenOption option : options) {
        if (option == StandardOpenOption.APPEND) {
            append = true;
        } else if (option == StandardOpenOption.TRUNCATE_EXISTING) {
            truncateExisting = true;
        } else if (option == StandardOpenOption.CREATE) {
            create = true;
        } else if (option == StandardOpenOption.CREATE_NEW) {
            createNew = true;
        } else if (option == StandardOpenOption.DELETE_ON_CLOSE) {
            deleteOnClose = true;
        } else if (option != StandardOpenOption.WRITE && !isIgnoredOpenOption(option)) {
            throw Messages.fileSystemProvider().unsupportedOpenOption(option);
        }
    }

    // append and truncateExisting contradict each other
    if (append && truncateExisting) {
        throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
    }

    return new OpenOptions(false, true, append, create, createNew, deleteOnClose, options);
}
 
Example 7
Source File: AlignedBuffersDirectFileIO.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Convert Java open options to native flags.
 *
 * @param modes java options.
 * @param log logger.
 * @param enableDirect flag for enabling option {@link IgniteNativeIoLib#O_DIRECT} .
 * @return native flags for open method.
 */
private static int setupOpenFlags(OpenOption[] modes, IgniteLogger log, boolean enableDirect) {
    int flags = enableDirect ? IgniteNativeIoLib.O_DIRECT : 0;
    List<OpenOption> openOptionList = Arrays.asList(modes);

    for (OpenOption mode : openOptionList) {
        if (mode == StandardOpenOption.READ) {
            flags |= openOptionList.contains(StandardOpenOption.WRITE)
                ? IgniteNativeIoLib.O_RDWR
                : IgniteNativeIoLib.O_RDONLY;
        }
        else if (mode == StandardOpenOption.WRITE) {
            flags |= openOptionList.contains(StandardOpenOption.READ)
                ? IgniteNativeIoLib.O_RDWR
                : IgniteNativeIoLib.O_WRONLY;
        }
        else if (mode == StandardOpenOption.CREATE)
            flags |= IgniteNativeIoLib.O_CREAT;
        else if (mode == StandardOpenOption.TRUNCATE_EXISTING)
            flags |= IgniteNativeIoLib.O_TRUNC;
        else if (mode == StandardOpenOption.SYNC)
            flags |= IgniteNativeIoLib.O_SYNC;
        else
            log.error("Unsupported open option [" + mode + "]");
    }

    return flags;
}
 
Example 8
Source File: BuilderOptions.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public void setOpenOptions ( final OpenOption[] openOptions )
{
    // always create a new array so that the result is independent of the old array
    if ( openOptions == null )
    {
        this.openOptions = new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING };
    }
    else
    {
        this.openOptions = Arrays.copyOf ( openOptions, openOptions.length );
    }
}
 
Example 9
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewOutputStreamExisting() throws IOException {
    addDirectory("/foo");
    addFile("/foo/bar");

    OpenOption[] options = { StandardOpenOption.WRITE };
    try (OutputStream output = fileSystem.newOutputStream(createPath("/foo/bar"), options)) {
        // don't do anything with the stream, there's a separate test for that
    }
    // verify that the file system can be used after closing the stream
    fileSystem.checkAccess(createPath("/foo/bar"));

    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/foo/bar")));
}
 
Example 10
Source File: CompatDx.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(
    int fileIndex, ByteDataView data, Set<String> descriptors, DiagnosticsHandler handler) {
  StandardOpenOption[] options = {
    StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING
  };
  try (OutputStream stream = new BufferedOutputStream(Files.newOutputStream(output, options))) {
    stream.write(data.getBuffer(), data.getOffset(), data.getLength());
  } catch (IOException e) {
    handler.error(new ExceptionDiagnostic(e, new PathOrigin(output)));
  }
}
 
Example 11
Source File: FileDataStorageManager.java    From herddb with Apache License 2.0 5 votes vote down vote up
@Override
public void writePage(String tableSpace, String tableName, long pageId, Collection<Record> newPage) throws DataStorageManagerException {
    // synch on table is done by the TableManager
    long _start = System.currentTimeMillis();
    Path tableDir = getTableDirectory(tableSpace, tableName);
    Path pageFile = getPageFile(tableDir, pageId);
    long size;

    try {
        if (pageodirect) {
            try (ODirectFileOutputStream odirect = new ODirectFileOutputStream(pageFile, O_DIRECT_BLOCK_BATCH,
                    StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
                size = writePage(newPage, null, odirect);
            }

        } else {
            try (ManagedFile file = ManagedFile.open(pageFile, requirefsync,
                    StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
                 SimpleBufferedOutputStream buffer = new SimpleBufferedOutputStream(file.getOutputStream(), COPY_BUFFERS_SIZE)) {

                size = writePage(newPage, file, buffer);
            }

        }
    } catch (IOException err) {
        throw new DataStorageManagerException(err);
    }

    long now = System.currentTimeMillis();
    long delta = (now - _start);

    if (LOGGER.isLoggable(Level.FINER)) {
        LOGGER.log(Level.FINER, "writePage {0} KBytes,{1} records, time {2} ms", new Object[]{(size / 1024) + "", newPage.size(), delta + ""});
    }
    dataPageWrites.registerSuccessfulEvent(delta, TimeUnit.MILLISECONDS);
}
 
Example 12
Source File: ResourceSvc.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
public WebResource writeCustomized(String fileName, Supplier<WebResource> source) throws IOException {
    WebResource original = source.get();
    byte[] bytes = original.asBytes();
    OpenOption[] overwrite = {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE};
    Path to = files.getCustomizationDirectory().resolve(fileName);
    Files.createDirectories(to.getParent());
    Files.write(to, bytes, overwrite);
    return original;
}
 
Example 13
Source File: FSDirectory.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public FSIndexOutput(String name) throws IOException {
  this(name, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
}
 
Example 14
Source File: OpenOptions.java    From sftp-fs with Apache License 2.0 4 votes vote down vote up
static OpenOptions forNewByteChannel(Set<? extends OpenOption> options) {

        boolean read = false;
        boolean write = false;
        boolean append = false;
        boolean truncateExisting = false;
        boolean create = false;
        boolean createNew = false;
        boolean deleteOnClose = false;

        for (OpenOption option : options) {
            if (option == StandardOpenOption.READ) {
                read = true;
            } else if (option == StandardOpenOption.WRITE) {
                write = true;
            } else if (option == StandardOpenOption.APPEND) {
                append = true;
            } else if (option == StandardOpenOption.TRUNCATE_EXISTING) {
                truncateExisting = true;
            } else if (option == StandardOpenOption.CREATE) {
                create = true;
            } else if (option == StandardOpenOption.CREATE_NEW) {
                createNew = true;
            } else if (option == StandardOpenOption.DELETE_ON_CLOSE) {
                deleteOnClose = true;
            } else if (!isIgnoredOpenOption(option)) {
                throw Messages.fileSystemProvider().unsupportedOpenOption(option);
            }
        }

        // as per Files.newByteChannel, if none of these options is given, default to read
        if (!read && !write && !append) {
            read = true;
        }

        // read contradicts with write, append, create and createNew; TRUNCATE_EXISTING is ignored in combination with READ
        if (read && (write || append || create || createNew)) {
            throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
        }

        // append and truncateExisting contract each other
        if (append && truncateExisting) {
            throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
        }

        // read and write contract each other; read and append contract each other; append and truncateExisting contract each other
        if ((read && write) || (read && append) || (append && truncateExisting)) {
            throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
        }

        return new OpenOptions(read, write, append, create, createNew, deleteOnClose, options);
    }
 
Example 15
Source File: FileDataStorageManager.java    From herddb with Apache License 2.0 4 votes vote down vote up
@Override
public void writeIndexPage(
        String tableSpace, String indexName,
        long pageId, DataWriter writer
) throws DataStorageManagerException {
    long _start = System.currentTimeMillis();
    Path tableDir = getIndexDirectory(tableSpace, indexName);

    Path pageFile = getPageFile(tableDir, pageId);
    long size;
    try {
        if (indexodirect) {
            try (ODirectFileOutputStream odirect = new ODirectFileOutputStream(pageFile, O_DIRECT_BLOCK_BATCH,
                    StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
                size = writeIndexPage(writer, null, odirect);
            }

        } else {
            try (ManagedFile file = ManagedFile.open(pageFile, requirefsync,
                    StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
                 SimpleBufferedOutputStream buffer = new SimpleBufferedOutputStream(file.getOutputStream(), COPY_BUFFERS_SIZE)) {

                size = writeIndexPage(writer, file, buffer);
            }
        }

    } catch (IOException err) {
        LOGGER.log(Level.SEVERE, "Failed to write on path: {0}", pageFile);
        Path path = pageFile;
        boolean exists;
        do {
            exists = Files.exists(path);

            if (exists) {
                LOGGER.log(Level.INFO,
                        "Path {0}: directory {1}, file {2}, link {3}, writable {4}, readable {5}, executable {6}",
                        new Object[] { path, Files.isDirectory(path), Files.isRegularFile(path),
                                Files.isSymbolicLink(path), Files.isWritable(path), Files.isReadable(path),
                                Files.isExecutable(path) });
            } else {
                LOGGER.log(Level.INFO, "Path {0} doesn't exists", path);
            }

            path = path.getParent();
        } while (path != null && !exists);

        throw new DataStorageManagerException(err);
    }

    long now = System.currentTimeMillis();
    long delta = (now - _start);
    if (LOGGER.isLoggable(Level.FINER)) {
        LOGGER.log(Level.FINER, "writePage {0} KBytes, time {2} ms", new Object[]{(size / 1024) + "", delta + ""});
    }
    indexPageWrites.registerSuccessfulEvent(delta, TimeUnit.MILLISECONDS);
}
 
Example 16
Source File: StaxDataStore.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new XML stream writer for writing the XML document.
 * If another {@code XMLStreamWriter} has already been created before this method call,
 * whether this method will succeed in creating a new writer depends on the storage type
 * (e.g. file or output stream).
 *
 * @param  target  the writer which will store the {@code XMLStreamWriter} reference.
 * @return a new writer for writing the XML data.
 * @throws DataStoreException if the output type is not recognized or the data store is closed.
 * @throws XMLStreamException if an error occurred while opening the XML file.
 * @throws IOException if an error occurred while preparing the output stream.
 */
final synchronized XMLStreamWriter createWriter(final StaxStreamWriter target)
        throws DataStoreException, XMLStreamException, IOException
{
    Object outputOrFile = storage;
    if (outputOrFile == null) {
        throw new DataStoreClosedException(getLocale(), getFormatName(), StandardOpenOption.WRITE);
    }
    switch (state) {
        default:       throw new AssertionError(state);
        case READING:  throw new ConcurrentReadException (getLocale(), getDisplayName());
        case WRITING:  throw new ConcurrentWriteException(getLocale(), getDisplayName());
        case START:    break;         // Stream already at the data start; nothing to do.
        case FINISHED: {
            if (reset()) break;
            throw new ForwardOnlyStorageException(getLocale(), getDisplayName(), StandardOpenOption.WRITE);
        }
    }
    /*
     * If the storage given by the user was not one of OutputStream, Writer or other type recognized
     * by OutputType, then maybe that storage was a Path, File or URL, in which case the constructor
     * should have opened an InputStream (not an OutputStream) for it. In some cases (e.g. reading a
     * channel opened on a file), the input stream can be converted to an output stream.
     */
    AutoCloseable output = stream;
    OutputType type = storageToWriter;
    if (type == null) {
        type   = OutputType.STREAM;
        output = IOUtilities.toOutputStream(output);
        if (output == null) {
            throw new UnsupportedStorageException(getLocale(), getFormatName(), storage, StandardOpenOption.WRITE);
        }
        outputOrFile = output;
        if (output != stream) {
            stream = output;
            mark();
        }
    }
    XMLStreamWriter writer = type.create(this, outputOrFile);
    if (indentation >= 0) {
        writer = new FormattedWriter(writer, indentation);
    }
    target.stream = output;
    state = WRITING;
    return writer;
}
 
Example 17
Source File: AgrestPostprocessor.java    From agrest with Apache License 2.0 4 votes vote down vote up
protected String extractTableOfContents(Document document, String output) {
    int start = output.indexOf("<div id=\"toc\" class=\"toc\">");
    if(start == -1) {
        // no toc found, exit
        return output;
    }

    String tocEndString = "</ul>\n</div>";
    int end = output.indexOf(tocEndString, start);
    if(end == -1) {
        // bad, no end..
        return output;
    }

    end += tocEndString.length() + 1;

    org.jsoup.nodes.Document tocDoc = Jsoup.parseBodyFragment(output.substring(start, end));
    tocDoc.select("ul").addClass("nav");
    tocDoc.select("a").addClass("nav-link");
    tocDoc.select("div#toc").addClass("toc-side");
    String toc = tocDoc.body().html();

    Object destDir = document.getOptions().get(Options.DESTINATION_DIR);
    Object docname = ((Map)document.getOptions().get(Options.ATTRIBUTES)).get("docname");

    Path path = FileSystems.getDefault().getPath((String) destDir, docname + ".toc.html");
    StandardOpenOption[] options = {
            StandardOpenOption.TRUNCATE_EXISTING,
            StandardOpenOption.CREATE,
            StandardOpenOption.WRITE
    };
    try(BufferedWriter br = Files.newBufferedWriter(path, options)) {
        br.write(toc, 0, toc.length());
        br.flush();
    } catch (IOException ex) {
        ex.printStackTrace(System.err);
    }

    if(start == 0) {
        return output.substring(end);
    }

    return output.substring(0, start) + output.substring(end);
}
 
Example 18
Source File: FileSerializationEventBusListener.java    From buck with Apache License 2.0 4 votes vote down vote up
public FileSerializationEventBusListener(Path outputPath) throws IOException {
  super(
      outputPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
}
 
Example 19
Source File: FileSystemProvider.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Opens a file, returning an input stream to read from the file. This
 * method works in exactly the manner specified by the {@link
 * Files#newInputStream} method.
 *
 * <p> The default implementation of this method opens a channel to the file
 * as if by invoking the {@link #newByteChannel} method and constructs a
 * stream that reads bytes from the channel. This method should be overridden
 * where appropriate.
 *
 * @param   path
 *          the path to the file to open
 * @param   options
 *          options specifying how the file is opened
 *
 * @return  a new input stream
 *
 * @throws  IllegalArgumentException
 *          if an invalid combination of options is specified
 * @throws  UnsupportedOperationException
 *          if an unsupported option is specified
 * @throws  IOException
 *          if an I/O error occurs
 * @throws  SecurityException
 *          In the case of the default provider, and a security manager is
 *          installed, the {@link SecurityManager#checkRead(String) checkRead}
 *          method is invoked to check read access to the file.
 */
public InputStream newInputStream(Path path, OpenOption... options)
    throws IOException
{
    if (options.length > 0) {
        for (OpenOption opt: options) {
            // All OpenOption values except for APPEND and WRITE are allowed
            if (opt == StandardOpenOption.APPEND ||
                opt == StandardOpenOption.WRITE)
                throw new UnsupportedOperationException("'" + opt + "' not allowed");
        }
    }
    ReadableByteChannel rbc = Files.newByteChannel(path, options);
    if (rbc instanceof FileChannelImpl) {
        ((FileChannelImpl) rbc).setUninterruptible();
    }
    return Channels.newInputStream(rbc);
}
 
Example 20
Source File: HttpResponse.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns a {@code BodyProcessor} which stores the response body in a
 * file opened with the given name. Has the same effect as calling
 * {@link #asFile(java.nio.file.Path, java.nio.file.OpenOption...) asFile}
 * with the standard open options {@code CREATE} and {@code WRITE}
 * <p>
 * The {@link HttpResponse} using this processor is available after the
 * entire response has been read.
 *
 * @param file the file to store the body in
 * @return a body processor
 */
public static BodyProcessor<Path> asFile(Path file) {
    return new ResponseProcessors.PathProcessor(
            file,
            StandardOpenOption.CREATE, StandardOpenOption.WRITE);
}