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:org.sakuli.services.forwarder.checkmk.CheckMKResultServiceImpl.java

private void writeToFile(Path file, String output) throws SakuliForwarderException {
    try {// w w  w  . java 2 s.com
        logger.info(String.format("Write file to '%s'", file));
        Files.write(file, output.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
        throw new SakuliForwarderException(e, String.format(
                "Unexpected error by writing the output for check_mk to the following file '%s'", file));
    }
}

From source file:org.basinmc.maven.plugins.minecraft.launcher.DownloadDescriptor.java

/**
 * Fetches the artifact from the server and stores it in a specified file.
 *//*  w w  w. j  ava  2  s  .  co  m*/
public void fetch(@Nonnull Path outputFile) throws IOException {
    HttpClient client = HttpClients.createMinimal();

    try {
        HttpGet request = new HttpGet(this.url.toURI());
        HttpResponse response = client.execute(request);

        StatusLine line = response.getStatusLine();

        if (line.getStatusCode() != 200) {
            throw new IOException(
                    "Unexpected status code: " + line.getStatusCode() + " - " + line.getReasonPhrase());
        }

        try (InputStream inputStream = response.getEntity().getContent()) {
            try (FileChannel fileChannel = FileChannel.open(outputFile, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                try (ReadableByteChannel inputChannel = Channels.newChannel(inputStream)) {
                    fileChannel.transferFrom(inputChannel, 0, Long.MAX_VALUE);
                }
            }
        }
    } catch (URISyntaxException ex) {
        throw new IOException("Received invalid URI from API: " + ex.getMessage(), ex);
    }
}

From source file:divconq.util.IOUtil.java

public static OperationResult saveEntireFile(Path dest, String content) {
    OperationResult or = new OperationResult();

    try {//from  www  .j av  a 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) {
        or.error(1, "Error saving file contents: " + x);
    }

    return or;
}

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 {//from w w  w .j  a v  a2 s. 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:com.bhuwan.eventregistration.business.boundary.EventRegistrationResource.java

@POST
@Path("{id}")
public void saveEventData(@PathParam("id") String id, JsonObject eventData)
        throws IOException, URISyntaxException {
    String path = getClass().getClassLoader().getResource("/eventdata/").getPath();
    String filePath = path + id + ".json";
    while (new File(filePath).exists()) {
        int fileId = Integer.valueOf(id) + 1;
        filePath = (path + fileId) + ".json";
    }//from   w  ww  . j  av a2 s  .  co m
    System.out.println(" filepath: " + filePath);
    Files.write(Paths.get(filePath), eventData.toString().getBytes(), StandardOpenOption.CREATE);
}

From source file:org.apache.marmotta.platform.ldp.services.LdpBinaryStoreServiceImpl.java

@Override
public boolean store(String resource, InputStream stream) {
    try {/*from  w ww.  j  a  v  a  2 s .  c  o  m*/
        Path file = getFile(resource);
        Files.createDirectories(file.getParent());

        try (OutputStream outputStream = Files.newOutputStream(file, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING)) {
            IOUtils.copy(stream, outputStream);
        }
        return true;
    } catch (URISyntaxException | IOException e) {
        log.error("{} resource cannot be stored on disk: {}", resource, e.getMessage());
        return false;
    }
}

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
 *///  w  w w .j  a  va2  s. c o  m
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:srebrinb.compress.sevenzip.SevenZOutputFile.java

/**
 * Opens file to write a 7z archive to./*from  w  ww.j av  a  2  s . c  o m*/
 *
 * @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:com.frostwire.gui.library.DownloadTask.java

@Override
public void run() {
    if (!isRunning()) {
        return;/*from ww w . j  ava  2s .c o  m*/
    }

    File lastFile = null;

    try {
        setProgress(0);

        if (!savePath.exists()) {
            savePath.mkdirs();
        }

        long totalBytes = getTotalBytes();
        long totalWritten = 0;

        for (int i = 0; i < fds.length; i++) {
            if (!isRunning()) {
                return;
            }

            currentFD = fds[i];

            GUIMediator.safeInvokeLater(new Runnable() {
                public void run() {
                    String status = String.format("%s from %s - %s", I18n.tr("Downloading"), device.getName(),
                            currentFD.title);
                    LibraryMediator.instance().getLibrarySearch().pushStatus(status);
                }
            });

            URL url = new URL(device.getDownloadURL(currentFD));

            InputStream is = null;
            OutputStream fos = null;

            try {
                is = url.openStream();

                String filename = OSUtils.escapeFilename(FilenameUtils.getName(currentFD.filePath));
                File file = buildFile(savePath, filename);
                Path incompleteFile = buildIncompleteFile(file).toPath();
                lastFile = file.getAbsoluteFile();

                fos = Files.newOutputStream(incompleteFile, StandardOpenOption.CREATE);// new FileOutputStream(incompleteFile);

                byte[] buffer = new byte[4 * 1024];
                int n = 0;

                while ((n = is.read(buffer, 0, buffer.length)) != -1) {
                    if (!isRunning()) {
                        return;
                    }

                    fos.write(buffer, 0, n);
                    fos.flush();
                    totalWritten += n;
                    setProgress((int) ((totalWritten * 100) / totalBytes));

                    if (getProgress() % 5 == 0) {
                        GUIMediator.safeInvokeLater(new Runnable() {
                            public void run() {
                                String status = String.format("%d%% %s from %s - %s", getProgress(),
                                        I18n.tr("Downloading"), device.getName(), currentFD.title);
                                LibraryMediator.instance().getLibrarySearch().pushStatus(status);
                            }
                        });
                    }

                    //System.out.println("Progress: " + getProgress() + " Total Written: " + totalWritten + " Total Bytes: " + totalBytes);
                }

                close(fos);
                Files.move(incompleteFile, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } finally {
                close(is);
                close(fos);
            }
        }

        setProgress(100);
    } catch (Throwable e) {
        e.printStackTrace();
        onError(e);

        GUIMediator.safeInvokeLater(new Runnable() {
            public void run() {
                LibraryMediator.instance().getLibrarySearch()
                        .pushStatus(I18n.tr("Wi-Fi download error. Please try again."));
            }
        });
    } finally {
        GUIMediator.safeInvokeLater(new Runnable() {
            public void run() {
                LibraryMediator.instance().getLibrarySearch().revertStatus();
            }
        });

        if (lastFile != null) {
            GUIMediator.launchExplorer(lastFile);
        }
    }

    stop();
}

From source file:com.khepry.utilities.GenericUtilities.java

public static void displayLogFile(String logFilePath, long logSleepMillis, String xsltFilePath,
        String xsldFilePath) {/*from w ww  . j  av a2s. com*/
    Logger.getLogger("").getHandlers()[0].close();
    // only display the log file
    // if the logSleepMillis property
    // is greater than zero milliseconds
    if (logSleepMillis > 0) {
        try {
            Thread.sleep(logSleepMillis);
            File logFile = new File(logFilePath);
            File xsltFile = new File(xsltFilePath);
            File xsldFile = new File(xsldFilePath);
            File tmpFile = File.createTempFile("tmpLogFile", ".xhtml", logFile.getParentFile());
            if (logFile.exists()) {
                if (xsltFile.exists() && xsldFile.exists()) {
                    String xslFilePath;
                    String xslFileName;
                    String dtdFilePath;
                    String dtdFileName;
                    try {
                        xslFileName = new File(logFilePath).getName().replace(".xhtml", ".xsl");
                        xslFilePath = logFile.getParentFile().toString().concat("/").concat(xslFileName);
                        FileUtils.copyFile(new File(xsltFilePath), new File(xslFilePath));
                        dtdFileName = new File(logFilePath).getName().replace(".xhtml", ".dtd");
                        dtdFilePath = logFile.getParentFile().toString().concat("/").concat(dtdFileName);
                        FileUtils.copyFile(new File(xsldFilePath), new File(dtdFilePath));
                    } catch (IOException ex) {
                        String message = Level.SEVERE.toString().concat(": ").concat(ex.getLocalizedMessage());
                        Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, message, ex);
                        GenericUtilities.outputToSystemErr(message, logSleepMillis > 0);
                        return;
                    }
                    BufferedWriter bw = Files.newBufferedWriter(Paths.get(tmpFile.getAbsolutePath()),
                            Charset.defaultCharset(), StandardOpenOption.CREATE);
                    List<String> logLines = Files.readAllLines(Paths.get(logFilePath),
                            Charset.defaultCharset());
                    for (String line : logLines) {
                        if (line.startsWith("<!DOCTYPE log SYSTEM \"logger.dtd\">")) {
                            bw.write("<!DOCTYPE log SYSTEM \"" + dtdFileName + "\">\n");
                            bw.write("<?xml-stylesheet type=\"text/xsl\" href=\"" + xslFileName + "\"?>\n");
                        } else {
                            bw.write(line.concat("\n"));
                        }
                    }
                    bw.write("</log>\n");
                    bw.close();
                }
                // the following statement is commented out because it's not quite ready for prime-time yet
                // Files.write(Paths.get(logFilePath), transformLogViaXSLT(logFilePath, xsltFilePath).getBytes(), StandardOpenOption.CREATE);
                Desktop.getDesktop().open(tmpFile);
            } else {
                Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, logFilePath,
                        new FileNotFoundException());
            }
        } catch (InterruptedException | IOException ex) {
            Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}