Example usage for java.nio.file StandardOpenOption CREATE

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

Introduction

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

Prototype

StandardOpenOption CREATE

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

Click Source Link

Document

Create a new file if it does not exist.

Usage

From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java

@Test
public void testAnnotateFileContentsDescClient() throws Exception {
    File f = new File("test-file");
    try {/*  www .j  av  a2  s . c  o  m*/
        Path p = f.toPath();
        ArrayList<String> lines = new ArrayList<>(1);
        lines.add(documentText);
        Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE);
        AnnotatedDocument result = apiDesc.annotateFileContents(f, Charset.forName("UTF-8"), documentMimeType);
        assertTrue(result.getText().contains("Barack"));
    } finally {
        f.delete();
    }
}

From source file:com.fizzed.stork.deploy.Archive.java

static private void unpackEntry(ArchiveInputStream ais, Path target) throws IOException {
    // always make sure parent dir exists
    Files.createDirectories(target.getParent());

    try (OutputStream os = Files.newOutputStream(target, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING)) {
        try (BufferedOutputStream bos = new BufferedOutputStream(os)) {
            int len = 0;
            byte[] BUFFER = new byte[1024];
            while ((len = ais.read(BUFFER)) != -1) {
                bos.write(BUFFER, 0, len);
            }/*from  w ww . j av a2s . c  o m*/
        }
    }
}

From source file:org.schedulesdirect.grabber.ProgramTask.java

@Override
public void run() {
    long start = System.currentTimeMillis();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.PROGRAMS, clnt.getHash(),
            clnt.getUserAgent(), clnt.getBaseUrl());
    try {//from   w  w  w .  j av a2s.c  o m
        JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(this.req), JSONArray.class);
        for (int i = 0; i < resp.length(); ++i) {
            JSONObject o = resp.getJSONObject(i);
            String id = o.optString("programID", "<unknown>");
            if (!JsonResponseUtils.isErrorResponse(o)) {
                if (id.startsWith("EP"))
                    seriesIds.add(Program.convertToSeriesId(id));
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                Files.write(p, o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
            } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.INVALID_PROGID
                    || JsonResponseUtils.getErrorCode(o) == ApiResponse.PROGRAMID_QUEUED) {
                String msg = String.format("Missing program object: %s", id);
                if (!logMissingAtDebug)
                    LOG.warn(msg);
                else
                    LOG.debug(msg);
                if (retrySet != null)
                    retrySet.add(id);
            } else
                throw new InvalidJsonObjectException("Error received for Program", o.toString(3));
        }
    } catch (JSONException | JsonParseException e) {
        Grabber.failedTask = true;
        LOG.error("JSONError!", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        Grabber.failedTask = true;
        LOG.error("IOError receiving program data; filling in empty program info for non-existent program ids!",
                e);
        try {
            JSONArray ids = this.req;
            for (int i = 0; i < ids.length(); ++i) {
                String id = ids.getString(i);
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                if (!Files.exists(p))
                    Files.write(p, Program.EMPTY_PROGRAM.getBytes(ZipEpgClient.ZIP_CHARSET));
            }
        } catch (Exception x) {
            LOG.error("Unexpected error!", x);
            throw new RuntimeException(x);
        }
    }
    LOG.info(String.format("Completed ProgramTask in %dms [%d programs]", System.currentTimeMillis() - start,
            this.req.length()));
}

From source file:org.cryptomator.ui.settings.SettingsProvider.java

private void save(Settings settings) {
    Objects.requireNonNull(settings);
    try {/* w w w.ja  v  a2  s . com*/
        final Path settingsPath = getSettingsPath();
        Files.createDirectories(settingsPath.getParent());
        final OutputStream out = Files.newOutputStream(settingsPath, StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
        objectMapper.writeValue(out, settings);
        LOG.info("Settings saved to " + settingsPath);
    } catch (IOException e) {
        LOG.error("Failed to save settings.", e);
    }
}

From source file:org.wikidata.wdtk.util.DirectoryManagerImpl.java

@Override
public long createFileAtomic(String fileName, InputStream inputStream) throws IOException {
    long fileSize;
    Path filePath = this.directory.resolve(fileName);
    Path fileTempPath = this.directory.resolve(fileName + ".part");

    try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
            FileChannel fc = FileChannel.open(fileTempPath, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)) {
        fileSize = fc.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
    }// ww  w  . j  ava 2  s.c o  m

    Files.move(fileTempPath, filePath);

    return fileSize;
}

From source file:io.druid.indexing.worker.executor.ExecutorLifecycle.java

@LifecycleStart
public void start() throws InterruptedException {
    final File taskFile = Preconditions.checkNotNull(taskExecutorConfig.getTaskFile(), "taskFile");
    final File statusFile = Preconditions.checkNotNull(taskExecutorConfig.getStatusFile(), "statusFile");
    final InputStream parentStream = Preconditions.checkNotNull(taskExecutorConfig.getParentStream(),
            "parentStream");

    try {/*  ww w .j a  v a 2  s  .  c  o m*/
        task = jsonMapper.readValue(taskFile, Task.class);

        log.info("Running with task: %s", jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(task));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    // Avoid running the same task twice on the same machine by locking the task base directory.

    final File taskLockFile = taskConfig.getTaskLockFile(task.getId());

    try {
        synchronized (this) {
            if (taskLockChannel == null && taskLockFileLock == null) {
                taskLockChannel = FileChannel.open(taskLockFile.toPath(), StandardOpenOption.CREATE,
                        StandardOpenOption.WRITE);

                log.info("Attempting to lock file[%s].", taskLockFile);
                final long startLocking = System.currentTimeMillis();
                final long timeout = DateTimes.utc(startLocking).plus(taskConfig.getDirectoryLockTimeout())
                        .getMillis();
                while (taskLockFileLock == null && System.currentTimeMillis() < timeout) {
                    taskLockFileLock = taskLockChannel.tryLock();
                    if (taskLockFileLock == null) {
                        Thread.sleep(100);
                    }
                }

                if (taskLockFileLock == null) {
                    throw new ISE("Could not acquire lock file[%s] within %,dms.", taskLockFile,
                            timeout - startLocking);
                } else {
                    log.info("Acquired lock file[%s] in %,dms.", taskLockFile,
                            System.currentTimeMillis() - startLocking);
                }
            } else {
                throw new ISE("Already started!");
            }
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    if (taskExecutorConfig.isParentStreamDefined()) {
        // Spawn monitor thread to keep a watch on parent's stdin
        // If stdin reaches eof, the parent is gone, and we should shut down
        parentMonitorExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    while (parentStream.read() != -1) {
                        // Toss the byte
                    }
                } catch (Exception e) {
                    log.error(e, "Failed to read from stdin");
                }

                // Kind of gross, but best way to kill the JVM as far as I know
                log.info("Triggering JVM shutdown.");
                System.exit(2);
            }
        });
    }

    // Won't hurt in remote mode, and is required for setting up locks in local mode:
    try {
        if (!task.isReady(taskActionClientFactory.create(task))) {
            throw new ISE("Task[%s] is not ready to run yet!", task.getId());
        }
    } catch (Exception e) {
        throw new ISE(e, "Failed to run task[%s] isReady", task.getId());
    }

    statusFuture = Futures.transform(taskRunner.run(task), new Function<TaskStatus, TaskStatus>() {
        @Override
        public TaskStatus apply(TaskStatus taskStatus) {
            try {
                log.info("Task completed with status: %s",
                        jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskStatus));

                final File statusFileParent = statusFile.getParentFile();
                if (statusFileParent != null) {
                    FileUtils.forceMkdir(statusFileParent);
                }
                jsonMapper.writeValue(statusFile, taskStatus);

                return taskStatus;
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    });
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerSecurityUpdaterTask.java

private void writeInternal(Path target, ByteBuffer data) throws IOException {
    try (FileChannel fc = FileChannel.open(target, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING)) {
        int numOfRetries = 0;
        FileLock lock = null;/*from   w w  w . jav  a 2 s .  c o  m*/
        while (lock == null && numOfRetries < 5) {
            try {
                lock = fc.tryLock();
                fc.write(data);
            } catch (OverlappingFileLockException ex) {
                lock = null;
                numOfRetries++;
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException iex) {
                    throw new IOException(iex);
                }
            } finally {
                if (lock != null) {
                    lock.release();
                }
            }
        }
    }
}

From source file:nl.salp.warcraft4j.casc.cdn.util.CascFileExtractor.java

private Optional<Path> extractFile(Path destination, long filenameHash)
        throws CascExtractionException, DataReadingException, DataParsingException {
    Optional<Path> file;
    if (isWritableFile(destination)) {
        try {//from  w  w  w  .j  a v a2  s  .  co m
            Files.createDirectories(destination.getParent());
            try (DataReader in = context.getFileDataReader(filenameHash);
                    OutputStream out = Files.newOutputStream(destination, StandardOpenOption.CREATE,
                            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                while (in.hasRemaining()) {
                    int chunkSize = (int) Math.min(CHUNK_SIZE, in.remaining());
                    byte[] chunk = in.readNext(DataTypeFactory.getByteArray(chunkSize));
                    out.write(chunk);
                }
                out.flush();
                file = Optional.of(destination);
            } catch (CascEntryNotFoundException e) {
                file = Optional.empty();
            }
        } catch (IOException e) {
            throw new CascExtractionException(
                    format("Error while extraction CASC file to %s: %s", destination, e.getMessage()), e);
        }
    } else {
        throw new CascExtractionException(format(
                "Unable to extract a file to %s, the path already exists and is not a file or not writable.",
                destination));
    }
    return file;
}

From source file:org.wso2.carbon.apimgt.core.util.APIFileUtils.java

/**
 * Writes the string content to a file/*  ww  w .j  ava2 s. c o  m*/
 *
 * @param path    path of the file to be written.
 * @param content Content to be written.
 * @throws APIMgtDAOException if an error occurs while writing to file
 */
public static void writeToFile(String path, String content) throws APIMgtDAOException {
    try {
        Files.write(Paths.get(path), content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
        String msg = "I/O error while writing to file at: " + path;
        log.error(msg, e);
        throw new APIMgtDAOException(msg, e);
    }
}

From source file:org.objectpocket.storage.blob.MultiZipBlobStore.java

@Override
public void writeBlobs(Set<Blob> blobs) throws IOException {
    if (blobs == null || blobs.isEmpty()) {
        return;/* w  ww  .ja  va2  s.  co  m*/
    }
    if (blobContainerIndex == null) {
        initIndexAndReadFileSystems();
    }
    FileSystem currentWriteFileSystem = null;
    for (Blob blob : blobs) {

        // get blob path
        String path = blob.getPath();
        if (path == null || path.trim().isEmpty()) {
            path = blob.getId();
        }
        path = path.replaceAll("\\\\", "/");

        String selectedBlobContainerName = null;

        // case 1: replace blob data
        String blobContainer = blobContainerIndex.get(path);
        if (blobContainer != null) {
            currentWriteFileSystem = getWriteFileSystem(blobContainer);
            selectedBlobContainerName = blobContainer;
        }

        // case 2: add blob data
        else {

            // create new blob container
            if (lastBlobContainer == null
                    || blob.getBytes().length + lastBlobContainerSize > MAX_BINARY_FILE_SIZE) {
                if (currentWriteFileSystem != null) {
                    currentWriteFileSystem.close();
                }
                createNextBinary();
            }

            currentWriteFileSystem = getWriteFileSystem(lastBlobContainer.getName());
            selectedBlobContainerName = lastBlobContainer.getName();
        }

        // write data to blob container
        String name = path;
        if (path.contains("/")) {
            name = path.substring(path.lastIndexOf("/"));
            path = path.substring(0, path.lastIndexOf("/"));
            while (path.startsWith("/")) {
                path = path.substring(1);
            }
            Path pathInZip = currentWriteFileSystem.getPath(path);
            if (!Files.exists(pathInZip)) {
                Files.createDirectories(pathInZip);
            }
            if (!Files.exists(pathInZip)) {
                throw new IOException("Could not create directory for blob. " + path);
            }
            path = path + name;
        }
        Path fileInZip = currentWriteFileSystem.getPath(path);
        try (OutputStream out = Files.newOutputStream(fileInZip, StandardOpenOption.CREATE)) {
            out.write(blob.getBytes());
        }
        blobContainerIndex.put(path, selectedBlobContainerName);
        blob.setPersisted();
        if (lastBlobContainer.getName().equals(selectedBlobContainerName)) {
            lastBlobContainerSize = lastBlobContainerSize + blob.getBytes().length;
        }

    }

    for (FileSystem fs : writeFileSystems.values()) {
        if (fs != null && fs.isOpen()) {
            fs.close();
        }
    }
    writeFileSystems.clear();

}