java.nio.file.StandardOpenOption#CREATE源码实例Demo

下面列出了java.nio.file.StandardOpenOption#CREATE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: nifi   文件: StatelessProcessSession.java
@Override
public void exportTo(FlowFile flowFile, final Path path, final boolean append) {
    flowFile = validateState(flowFile);
    if (flowFile == null || path == null) {
        throw new IllegalArgumentException("argument cannot be null");
    }
    if (!(flowFile instanceof StatelessFlowFile)) {
        throw new IllegalArgumentException("Cannot export a flow file that I did not create");
    }
    StatelessFlowFile statelessFlowFile = (StatelessFlowFile) flowFile;

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

    try (final OutputStream out = Files.newOutputStream(path, mode)) {
        if (statelessFlowFile.materializeContent)
            statelessFlowFile.materializeData();
        copyTo(statelessFlowFile.getDataStream(), out);
    } catch (final IOException e) {
        throw new FlowFileAccessException(e.toString(), e);
    }
}
 
源代码2 项目: localization_nifi   文件: MockProcessSession.java
@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);
    }
}
 
@Override
public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException {
    if (claim == null) {
        if (append) {
            return 0L;
        }
        Files.createFile(destination);
        return 0L;
    }

    final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
    try (final InputStream in = read(claim);
            final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) {

        if (offset > 0) {
            StreamUtils.skip(in, offset);
        }

        StreamUtils.copy(in, destinationStream, length);
        return length;
    }
}
 
源代码4 项目: nifi   文件: VolatileContentRepository.java
@Override
public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException {
    if (claim == null) {
        if (append) {
            return 0L;
        }
        Files.createFile(destination);
        return 0L;
    }

    final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
    try (final InputStream in = read(claim);
            final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) {

        if (offset > 0) {
            StreamUtils.skip(in, offset);
        }

        StreamUtils.copy(in, destinationStream, length);
        return length;
    }
}
 
源代码5 项目: WarpPI   文件: HardwareStorageUtils.java
@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);
}
 
源代码6 项目: WarpPI   文件: DesktopStorageUtils.java
@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);
}
 
源代码7 项目: sftp-fs   文件: SFTPFileSystemTest.java
@Test
public void testNewOutputStreamExistingCreateDeleteOnClose() throws IOException {
    addDirectory("/foo");
    addFile("/foo/bar");

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

    assertTrue(Files.isDirectory(getPath("/foo")));
    assertFalse(Files.exists(getPath("/foo/bar")));
}
 
源代码8 项目: logbook   文件: FileUtils.java
/**
 * 報告書をCSVファイルに書き込む
 *
 * @param path ファイル
 * @param header ヘッダー
 * @param body 内容
 * @param applend 追記フラグ
 * @throws IOException
 */
public static void writeCsv(Path path, String[] header, List<String[]> body, boolean applend)
        throws IOException {
    OpenOption[] options;
    if (applend) {
        options = new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.APPEND };
    } else {
        options = new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING };
    }
    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path, options))) {
        if (!Files.exists(path) || (Files.size(path) <= 0)) {
            out.write(StringUtils.join(header, ',').getBytes(AppConstants.CHARSET));
            out.write("\r\n".getBytes(AppConstants.CHARSET));
        }
        for (String[] colums : body) {
            out.write(StringUtils.join(colums, ',').getBytes(AppConstants.CHARSET));
            out.write("\r\n".getBytes(AppConstants.CHARSET));
        }
    }
}
 
源代码9 项目: vividus   文件: CsvFileCreator.java
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());
    }
}
 
源代码10 项目: ignite   文件: AlignedBuffersDirectFileIO.java
/**
 * 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;
}
 
源代码11 项目: sftp-fs   文件: OpenOptions.java
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);
}
 
源代码12 项目: sftp-fs   文件: SFTPFileSystemTest.java
@Test
public void testNewOutputStreamExistingCreate() throws IOException {
    addDirectory("/foo");
    addFile("/foo/bar");

    OpenOption[] options = { StandardOpenOption.CREATE };
    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")));
}
 
源代码13 项目: sftp-fs   文件: SFTPFileSystemTest.java
@Test
public void testNewOutputStreamNonExistingCreate() throws IOException {
    addDirectory("/foo");

    OpenOption[] options = { StandardOpenOption.CREATE };
    try (OutputStream input = fileSystem.newOutputStream(createPath("/foo/bar"), options)) {
        // don't do anything with the stream, there's a separate test for that
    } finally {
        assertTrue(Files.isDirectory(getPath("/foo")));
        assertTrue(Files.isRegularFile(getPath("/foo/bar")));
    }
}
 
源代码14 项目: sftp-fs   文件: SFTPFileSystemTest.java
@Test
public void testNewOutputStreamNonExistingCreateDeleteOnClose() throws IOException {
    addDirectory("/foo");

    OpenOption[] options = { StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE };
    try (OutputStream input = fileSystem.newOutputStream(createPath("/foo/bar"), options)) {
        // don't do anything with the stream, there's a separate test for that
        // we can't check here that /foo/bar exists, because it will only be stored in the file system once the stream is closed
    } finally {
        assertTrue(Files.isDirectory(getPath("/foo")));
        assertFalse(Files.exists(getPath("/foo/bar")));
        assertEquals(0, getChildCount("/foo"));
    }
}
 
源代码15 项目: indexr   文件: DPColumn.java
private void openWriteFiles() {
    try {
        OpenOption[] writeOptions = new StandardOpenOption[]{
                StandardOpenOption.WRITE,
                StandardOpenOption.CREATE};

        packFileWrite = FileChannel.open(packFilePath, writeOptions);
        dpnFileWrite = FileChannel.open(dpnFilePath, writeOptions);
        indexFileWrite = FileChannel.open(indexFilePath, writeOptions);
        extIndexFileWrite = FileChannel.open(extIndexFilePath, writeOptions);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
源代码16 项目: packagedrone   文件: BuilderOptions.java
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 );
    }
}
 
源代码17 项目: agrest   文件: AgrestPostprocessor.java
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);
}
 
源代码18 项目: buck   文件: FileSerializationEventBusListener.java
public FileSerializationEventBusListener(Path outputPath) throws IOException {
  super(
      outputPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
}
 
源代码19 项目: herddb   文件: FileDataStorageManager.java
@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);
}
 
源代码20 项目: sftp-fs   文件: OpenOptions.java
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);
    }