Example usage for java.nio.file StandardOpenOption WRITE

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

Introduction

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

Prototype

StandardOpenOption WRITE

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

Click Source Link

Document

Open for write access.

Usage

From source file:com.willwinder.universalgcodesender.model.GUIBackendPreprocessorTest.java

/**
 * Test of preprocessAndExportToFile method, of class GUIBackend.
 *///ww  w.ja  va2  s .com
@Test
public void testRegularPreprocessAndExportToFile() throws Exception {
    System.out.println("regularPreprocessAndExportToFile");
    GUIBackend backend = new GUIBackend();
    GcodeParser gcp = new GcodeParser();
    // Double all the commands that go in.
    gcp.addCommandProcessor(commandDoubler);
    gcp.addCommandProcessor(new CommentProcessor());

    // Create input file, comment-only line shouldn't be processed twice.
    List<String> lines = Arrays.asList("line one", "; comment", "line two");
    Files.write(inputFile, lines, Charset.defaultCharset(), StandardOpenOption.WRITE);

    backend.preprocessAndExportToFile(gcp, inputFile.toFile(), outputFile.toFile());

    List<String> expectedResults = Arrays.asList("line one", "line one", "", "line two", "line two");

    try (GcodeStreamReader reader = new GcodeStreamReader(outputFile.toFile())) {
        Assert.assertEquals(expectedResults.size(), reader.getNumRows());

        for (String expected : expectedResults) {
            Assert.assertEquals(expected, reader.getNextCommand().getCommandString());
        }
    }
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRegularFile() throws IOException {
    final Path tempDir = Files.createTempDirectory("ds3_file_object_putter_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {//  w  ww.ja va2s.c o m
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        getFileWithPutter(tempDir, tempPath);
    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:io.druid.query.groupby.epinephelinae.LimitedTemporaryStorage.java

/**
 * Create a new temporary file. All methods of the returned output stream may throw
 * {@link TemporaryStorageFullException} if the temporary storage area fills up.
 *
 * @return output stream to the file// w w w .  j  a v a2s .  c  o  m
 *
 * @throws TemporaryStorageFullException if the temporary storage area is full
 * @throws IOException                   if something goes wrong while creating the file
 */
public LimitedOutputStream createFile() throws IOException {
    if (bytesUsed.get() >= maxBytesUsed) {
        throw new TemporaryStorageFullException(maxBytesUsed);
    }

    synchronized (files) {
        if (closed) {
            throw new ISE("Closed");
        }

        FileUtils.forceMkdir(storageDirectory);

        final File theFile = new File(storageDirectory, StringUtils.format("%08d.tmp", files.size()));
        final EnumSet<StandardOpenOption> openOptions = EnumSet.of(StandardOpenOption.CREATE_NEW,
                StandardOpenOption.WRITE);

        final FileChannel channel = FileChannel.open(theFile.toPath(), openOptions);
        files.add(theFile);
        return new LimitedOutputStream(theFile, Channels.newOutputStream(channel));
    }
}

From source file:io.gravitee.maven.plugins.json.schema.generator.mojo.Output.java

/**
 * Create the JSON file associated to the JSON Schema
 *
 * @param schema the JSON schema to write into file
 *///from  w w  w.ja va2  s  .com
private void createJsonFile(JsonSchema schema) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);

        // replace all : with _ this is a reserved character in some file systems
        Path outputPath = Paths.get(
                config.getOutputDirectory() + File.separator + schema.getId().replaceAll(":", "_") + ".json");
        Files.write(outputPath, json.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING);
        config.getLogger().info("Created JSON Schema: " + outputPath.normalize().toAbsolutePath().toString());
    } catch (JsonProcessingException e) {
        config.getLogger().warn("Unable to display schema " + schema.getId(), e);
    } catch (Exception e) {
        config.getLogger().warn("Unable to write Json file for schema " + schema.getId(), e);
    }
}

From source file:org.aksw.gerbil.datasets.DatahubNIFConfig.java

/**
 * We have to synchronize this method. Otherwise every experiment thread would check the file and try to download
 * the data or try to use the file even the download hasn't been completed.
 *///from   w ww .ja  va2  s.  com
@Override
protected synchronized TopicDataset loadDataset() throws Exception {
    String nifFile = GerbilConfiguration.getInstance().getString(DATAHUB_DATASET_FILE_PROPERTY_NAME)
            + getName();
    logger.debug("FILE {}", nifFile);
    File f = new File(nifFile);
    if (!f.exists()) {
        logger.debug("file {} does not exist. need to download", nifFile);
        String data = rt.getForObject(datasetUrl, String.class);
        Path path = Paths.get(nifFile);
        Files.createDirectories(path.getParent());
        Path file = Files.createFile(path);
        Files.write(file, data.getBytes(), StandardOpenOption.WRITE);
    }
    FileBasedNIFDataset dataset = new FileBasedNIFDataset(wikiApi, nifFile, getName(), Lang.TTL);
    dataset.init();
    return dataset;
}

From source file:srebrinb.compress.sevenzip.SevenZOutputFile.java

/**
 * Opens file to write a 7z archive to./*from   w ww . j  ava2s  . c  om*/
 *
 * @param filename the file to write to
 * @throws IOException if opening the file fails
 */
public SevenZOutputFile(final File filename) throws IOException {
    this(Files.newByteChannel(filename.toPath(), EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE,
            StandardOpenOption.TRUNCATE_EXISTING)));
}

From source file:nl.jk_5.nailed.plugin.nmm.NmmMappack.java

@Override
public void prepareWorld(File destination, SettableFuture<Void> future) {
    HttpClient httpClient = HttpClientBuilder.create().build();
    try {/*from   www  .j  a  v  a 2  s.com*/
        String mappack = this.path.split("/", 2)[1];
        HttpGet request = new HttpGet("http://nmm.jk-5.nl/" + this.path + "/versions.json");
        HttpResponse response = httpClient.execute(request);
        MappackInfo list = NmmPlugin.gson.fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"),
                MappackInfo.class);

        HttpGet request2 = new HttpGet(
                "http://nmm.jk-5.nl/" + this.path + "/" + mappack + "-" + list.latest + ".zip");
        HttpEntity response2 = httpClient.execute(request2).getEntity();
        if (response2 != null) {
            File mappackZip = new File(destination, "mappack.zip");
            try (ReadableByteChannel source = Channels.newChannel(response2.getContent());
                    FileChannel out = FileChannel.open(mappackZip.toPath(), StandardOpenOption.CREATE_NEW,
                            StandardOpenOption.WRITE)) {
                out.transferFrom(source, 0, Long.MAX_VALUE);
            }
            ZipUtils.extract(mappackZip, destination);
            mappackZip.delete();
            this.dir = destination;
            File dataDir = new File(destination, ".data");
            dataDir.mkdir();
            File metadataLocation = new File(dataDir, "game.xml");
            new File(destination, "game.xml").renameTo(metadataLocation);
            new File(destination, "scripts").renameTo(new File(dataDir, "scripts"));
            File worldsDir = new File(destination, "worlds");
            for (File f : worldsDir.listFiles()) {
                f.renameTo(new File(destination, f.getName()));
            }
            worldsDir.delete();
            //metadata = XmlMappackMetadata.fromFile(metadataLocation);
            future.set(null);
        } else {
            future.setException(new RuntimeException(
                    "Got an empty response while downloading mappack " + this.path + " from nmm.jk-5.nl"));
        }
    } catch (Exception e) {
        future.setException(
                new RuntimeException("Was not able to download mappack " + this.path + " from nmm.jk-5.nl", e));
    }
}

From source file:org.cryptomator.webdav.jackrabbit.resources.EncryptedDir.java

private void addMemberFile(DavResource resource, InputContext inputContext) throws DavException {
    final Path childPath = ResourcePathUtils.getPhysicalPath(resource);
    SeekableByteChannel channel = null;
    try {//from   w w w .  jav  a 2 s  .c  o  m
        channel = Files.newByteChannel(childPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        cryptor.encryptFile(inputContext.getInputStream(), channel);
    } catch (SecurityException e) {
        throw new DavException(DavServletResponse.SC_FORBIDDEN, e);
    } catch (IOException e) {
        LOG.error("Failed to create file.", e);
        throw new IORuntimeException(e);
    } finally {
        IOUtils.closeQuietly(channel);
        IOUtils.closeQuietly(inputContext.getInputStream());
    }
}

From source file:io.pravega.segmentstore.storage.impl.extendeds3.S3FileSystemImpl.java

@Synchronized
@Override//  w  w w  .  j  ava 2  s.c  o  m
public void putObject(String bucketName, String key, Range range, Object content) {

    Path path = Paths.get(this.baseDir, bucketName, key);
    try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) {

        long startOffset = range.getFirst();
        long length = range.getLast() + 1 - range.getFirst();
        do {
            long bytesTransferred = channel.transferFrom(Channels.newChannel((InputStream) content),
                    range.getFirst(), range.getLast() + 1 - range.getFirst());
            length -= bytesTransferred;
            startOffset += bytesTransferred;
        } while (length > 0);

        AclSize aclKey = aclMap.get(key);
        aclMap.put(key, aclKey.withSize(range.getLast() + 1));
    } catch (IOException e) {
        throw new S3Exception("NoObject", 404, "NoSuchKey", key);
    }
}

From source file:divconq.util.IOUtil.java

public static boolean saveEntireFile2(Path dest, String content) {
    try {/*from www .j a  va 2 s. c  o  m*/
        Files.createDirectories(dest.getParent());
        Files.write(dest, Utf8Encoder.encode(content), StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.SYNC);
    } catch (Exception x) {
        return false;
    }

    return true;
}