Example usage for java.nio.file StandardOpenOption CREATE_NEW

List of usage examples for java.nio.file StandardOpenOption CREATE_NEW

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption CREATE_NEW.

Prototype

StandardOpenOption CREATE_NEW

To view the source code for java.nio.file StandardOpenOption CREATE_NEW.

Click Source Link

Document

Create a new file, failing if the file already exists.

Usage

From source file:org.apache.kylin.cube.inmemcubing.ConcurrentDiskStore.java

private void openWriteChannel(long startOffset) throws IOException {
    if (startOffset > 0) { // TODO does not support append yet
        writeChannel = FileChannel.open(diskFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND,
                StandardOpenOption.WRITE);
    } else {//from ww w  .  j  a  v  a 2 s.c  o  m
        diskFile.delete();
        writeChannel = FileChannel.open(diskFile.toPath(), StandardOpenOption.CREATE_NEW,
                StandardOpenOption.WRITE);
    }
}

From source file:org.apache.metron.dataloads.nonbulk.flatfile.SimpleEnrichmentFlatFileLoaderIntegrationTest.java

@BeforeClass
public static void setup() throws Exception {
    UnitTestHelper.setJavaLoggingLevel(Level.SEVERE);
    Map.Entry<HBaseTestingUtility, Configuration> kv = HBaseUtil.INSTANCE.create(true);
    config = kv.getValue();//from   w w w  .j  av a2s. c o  m
    testUtil = kv.getKey();
    testTable = testUtil.createTable(Bytes.toBytes(tableName), Bytes.toBytes(cf));
    zookeeperUrl = getZookeeperUrl(config.get("hbase.zookeeper.quorum"),
            testUtil.getZkCluster().getClientPort());
    setupGlobalConfig(zookeeperUrl);

    for (Result r : testTable.getScanner(Bytes.toBytes(cf))) {
        Delete d = new Delete(r.getRow());
        testTable.delete(d);
    }

    if (lineByLineExtractorConfigFile.exists()) {
        lineByLineExtractorConfigFile.delete();
    }
    Files.write(lineByLineExtractorConfigFile.toPath(), lineByLineExtractorConfig.getBytes(),
            StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING);
    if (wholeFileExtractorConfigFile.exists()) {
        wholeFileExtractorConfigFile.delete();
    }
    Files.write(wholeFileExtractorConfigFile.toPath(), wholeFileExtractorConfig.getBytes(),
            StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING);
    if (stellarExtractorConfigFile.exists()) {
        stellarExtractorConfigFile.delete();
    }
    Files.write(stellarExtractorConfigFile.toPath(),
            stellarExtractorConfig.replace("%ZK_QUORUM%", zookeeperUrl).getBytes(),
            StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING);
    if (customLineByLineExtractorConfigFile.exists()) {
        customLineByLineExtractorConfigFile.delete();
    }
    Files.write(
            customLineByLineExtractorConfigFile.toPath(), customLineByLineExtractorConfig
                    .replace("%EXTRACTOR_CLASS%", CSVExtractor.class.getName()).getBytes(),
            StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING);
    if (file1.exists()) {
        file1.delete();
    }
    Files.write(file1.toPath(), "google1.com,1,foo2\n".getBytes(), StandardOpenOption.CREATE_NEW,
            StandardOpenOption.TRUNCATE_EXISTING);
    if (file2.exists()) {
        file2.delete();
    }
    Files.write(file2.toPath(), "google2.com,2,foo2\n".getBytes(), StandardOpenOption.CREATE_NEW,
            StandardOpenOption.TRUNCATE_EXISTING);

    if (multilineFile.exists()) {
        multilineFile.delete();
    }
    if (multilineGzFile.exists()) {
        multilineGzFile.delete();
    }
    if (multilineGzFile.exists()) {
        multilineZipFile.delete();
    }
    PrintWriter[] pws = new PrintWriter[] {};
    try {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(multilineZipFile));
        ZipEntry entry = new ZipEntry("file");
        zos.putNextEntry(entry);
        pws = new PrintWriter[] { new PrintWriter(multilineFile), new PrintWriter(zos),
                new PrintWriter(new GZIPOutputStream(new FileOutputStream(multilineGzFile))) };
        for (int i = 0; i < NUM_LINES; ++i) {
            for (PrintWriter pw : pws) {
                pw.println("google" + i + ".com," + i + ",foo" + i);
            }
        }
    } finally {
        for (PrintWriter pw : pws) {
            pw.close();
        }
    }

}

From source file:org.apache.streams.plugins.StreamsScalaSourceGenerator.java

private void writeFile(String pojoFile, String pojoScala) {
    try {//from   w  w w  . j  a va 2s.  c om
        File path = new File(pojoFile);
        File dir = path.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Files.write(Paths.get(pojoFile), pojoScala.getBytes(), StandardOpenOption.CREATE_NEW);
    } catch (Exception ex) {
        LOGGER.error("Write Exception: {}", ex);
    }
}

From source file:org.apache.streams.util.schema.FileUtil.java

/**
 * writeFile./*from w w  w . j  a  v  a2 s  . c  o  m*/
 * @param resourceFile resourceFile
 * @param resourceContent resourceContent
 */
public static void writeFile(String resourceFile, String resourceContent) {
    try {
        File path = new File(resourceFile);
        File dir = path.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Files.write(Paths.get(resourceFile), resourceContent.getBytes(), StandardOpenOption.CREATE_NEW);
    } catch (Exception ex) {
        LOGGER.error("Write Exception: {}", ex);
    }
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemImpl.java

void createDirectory(CryptoPath cleartextDir, FileAttribute<?>... attrs) throws IOException {
    CryptoPath cleartextParentDir = cleartextDir.getParent();
    if (cleartextParentDir == null) {
        return;/* w  w w .ja v  a2  s  .  c  om*/
    }
    Path ciphertextParentDir = cryptoPathMapper.getCiphertextDirPath(cleartextParentDir);
    if (!Files.exists(ciphertextParentDir)) {
        throw new NoSuchFileException(cleartextParentDir.toString());
    }
    Path ciphertextFile = cryptoPathMapper.getCiphertextFilePath(cleartextDir, CiphertextFileType.FILE);
    if (Files.exists(ciphertextFile)) {
        throw new FileAlreadyExistsException(cleartextDir.toString());
    }
    Path ciphertextDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextDir, CiphertextFileType.DIRECTORY);
    boolean success = false;
    try {
        Directory ciphertextDir = cryptoPathMapper.getCiphertextDir(cleartextDir);
        try (FileChannel channel = FileChannel.open(ciphertextDirFile,
                EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE), attrs)) {
            channel.write(ByteBuffer.wrap(ciphertextDir.dirId.getBytes(UTF_8)));
        }
        Files.createDirectories(ciphertextDir.path);
        success = true;
    } finally {
        if (!success) {
            Files.delete(ciphertextDirFile);
            dirIdProvider.delete(ciphertextDirFile);
        }
    }
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemProviderIntegrationTest.java

@Test
public void testOpenAndCloseFileChannel() throws IOException {
    FileSystem fs = CryptoFileSystemProvider.newFileSystem(tmpPath,
            cryptoFileSystemProperties().withPassphrase("asd").build());
    try (FileChannel ch = FileChannel.open(fs.getPath("/foo"),
            EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW))) {
        Assert.assertTrue(ch instanceof CryptoFileChannel);
    }/*  www  .j  a va 2 s .c  o  m*/
}

From source file:org.cryptomator.ui.InitializeController.java

@FXML
protected void initializeVault(ActionEvent event) {
    setControlsDisabled(true);/* w w w .j  a va  2  s.c o  m*/
    if (!isDirectoryEmpty() && !shouldEncryptExistingFiles()) {
        return;
    }
    final String masterKeyFileName = usernameField.getText() + Aes256Cryptor.MASTERKEY_FILE_EXT;
    final Path masterKeyPath = directory.getPath().resolve(masterKeyFileName);
    final CharSequence password = passwordField.getCharacters();
    OutputStream masterKeyOutputStream = null;
    try {
        progressIndicator.setVisible(true);
        masterKeyOutputStream = Files.newOutputStream(masterKeyPath, StandardOpenOption.WRITE,
                StandardOpenOption.CREATE_NEW);
        directory.getCryptor().encryptMasterKey(masterKeyOutputStream, password);
        final Future<?> futureDone = FXThreads.runOnBackgroundThread(this::encryptExistingContents);
        FXThreads.runOnMainThreadWhenFinished(futureDone, (result) -> {
            progressIndicator.setVisible(false);
            progressIndicator.setVisible(false);
            directory.getCryptor().swipeSensitiveData();
            if (listener != null) {
                listener.didInitialize(this);
            }
        });
    } catch (FileAlreadyExistsException ex) {
        setControlsDisabled(false);
        progressIndicator.setVisible(false);
        messageLabel.setText(localization.getString("initialize.messageLabel.alreadyInitialized"));
    } catch (InvalidPathException ex) {
        setControlsDisabled(false);
        progressIndicator.setVisible(false);
        messageLabel.setText(localization.getString("initialize.messageLabel.invalidPath"));
    } catch (IOException ex) {
        setControlsDisabled(false);
        progressIndicator.setVisible(false);
        LOG.error("I/O Exception", ex);
    } finally {
        usernameField.setText(null);
        passwordField.swipe();
        retypePasswordField.swipe();
        IOUtils.closeQuietly(masterKeyOutputStream);
    }
}

From source file:org.hyperledger.fabric.sdk.testutils.TestConfig.java

/**
 * Returns the appropriate Network Config YAML file based on whether TLS is currently
 * enabled or not/*  ww  w.j a  v  a2s.  c om*/
 *
 * @return The appropriate Network Config YAML file
 */
public File getTestNetworkConfigFileYAML() {
    String fname = runningTLS ? "network-config-tls.yaml" : "network-config.yaml";
    String pname = "src/test/fixture/sdkintegration/network_configs/";
    File ret = new File(pname, fname);

    if (!"localhost".equals(LOCALHOST) || isFabricVersionAtOrAfter("1.3")) {
        // change on the fly ...
        File temp = null;

        try {
            //create a temp file
            temp = File.createTempFile(fname, "-FixedUp.yaml");

            if (temp.exists()) { //For testing start fresh
                temp.delete();
            }

            byte[] data = Files.readAllBytes(Paths.get(ret.getAbsolutePath()));

            String sourceText = new String(data, StandardCharsets.UTF_8);

            sourceText = sourceText.replaceAll("https://localhost", "https://" + LOCALHOST);
            sourceText = sourceText.replaceAll("http://localhost", "http://" + LOCALHOST);
            sourceText = sourceText.replaceAll("grpcs://localhost", "grpcs://" + LOCALHOST);
            sourceText = sourceText.replaceAll("grpc://localhost", "grpc://" + LOCALHOST);

            if (isFabricVersionAtOrAfter("1.3")) {
                //eventUrl: grpc://localhost:8053
                sourceText = sourceText.replaceAll("(?m)^[ \\t]*eventUrl:", "# eventUrl:");
            }

            Files.write(Paths.get(temp.getAbsolutePath()), sourceText.getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING,
                    StandardOpenOption.WRITE);

            if (!Objects.equals("true", System.getenv(ORG_HYPERLEDGER_FABRIC_SDK_TEST_FABRIC_HOST + "_KEEP"))) {
                temp.deleteOnExit();
            } else {
                System.err.println("produced new network-config.yaml file at:" + temp.getAbsolutePath());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        ret = temp;
    }

    return ret;
}

From source file:org.neo4j.io.pagecache.PageCacheTest.java

@Test(timeout = SEMI_LONG_TIMEOUT_MILLIS)
public void mustThrowOnUnsupportedOpenOptions() throws Exception {
    getPageCache(fs, maxPages, pageCachePageSize, PageCacheTracer.NULL);
    verifyMappingWithOpenOptionThrows(StandardOpenOption.CREATE_NEW);
    verifyMappingWithOpenOptionThrows(StandardOpenOption.SYNC);
    verifyMappingWithOpenOptionThrows(StandardOpenOption.DSYNC);
    verifyMappingWithOpenOptionThrows(new OpenOption() {
        @Override//from w w  w . j a  v a2 s. com
        public String toString() {
            return "NonStandardOpenOption";
        }
    });
}

From source file:org.obsidianbox.obsidian.message.builtin.AddFileMessage.java

@Override
public void handle(Game game, EntityPlayer player) {
    // Re-create the file
    final Path addonJarPath = Paths.get(CommonFileSystem.ADDONS_PATH.toString(), addonIdentifier);
    try {/*from   w  w w  . j a v  a2 s  .  co  m*/
        Files.write(addonJarPath, data, StandardOpenOption.CREATE_NEW);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    try {
        game.getAddonManager().loadAddon(addonJarPath);
    } catch (InvalidAddonException | InvalidDescriptionException e) {
        e.printStackTrace();
    }
    Minecraft.getMinecraft().scheduleResourcesRefresh();
}