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:net.dv8tion.jda.utils.SimpleLog.java

private static void logToFiles(String msg, Level level) {
    Set<File> files = collectFiles(level);
    for (File file : files) {
        try {/*  ww w. j a  va 2s.c  om*/
            Files.write(file.toPath(), (msg + '\n').getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);
        } catch (IOException e) {
            JDAImpl.LOG.fatal("Could not write log to logFile...");
            JDAImpl.LOG.log(e);
        }
    }
}

From source file:com.github.jinahya.simple.file.back.LocalFileBackTest.java

@Test(enabled = true, invocationCount = 1)
public void read() throws IOException, FileBackException {

    fileContext.fileOperationSupplier(() -> FileOperation.READ);

    final ByteBuffer fileKey = randomFileKey();
    fileContext.sourceKeySupplier(() -> fileKey);

    final Path leafPath = LocalFileBack.leafPath(rootPath, fileKey, true);

    final byte[] fileBytes = randomFileBytes();
    final boolean fileWritten = Files.isRegularFile(leafPath) || current().nextBoolean();
    if (fileWritten) {
        Files.write(leafPath, fileBytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        logger.trace("file written");
    }//from   ww w.j a  v a  2s  .c o  m

    fileContext.sourceChannelConsumer(v -> {
        final byte[] actual = new byte[fileBytes.length];
        try {
            IOUtils.readFully(Channels.newInputStream(v), actual);
            if (fileWritten) {
                assertEquals(actual, fileBytes);
            }
        } catch (final IOException ioe) {
            fail("failed to read from source channel", ioe);
        }
    });

    final ByteArrayOutputStream targetStream = new ByteArrayOutputStream();
    fileContext.targetChannelSupplier(() -> {
        return Channels.newChannel(targetStream);
    });

    fileBack.operate(fileContext);

    if (fileWritten) {
        assertEquals(targetStream.toByteArray(), fileBytes);
    }
}

From source file:com.google.cloud.dataflow.sdk.io.TextIOTest.java

License:asdf

private GcsUtil buildMockGcsUtil() throws IOException {
    GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class);

    // Any request to open gets a new bogus channel
    Mockito.when(mockGcsUtil.open(Mockito.any(GcsPath.class))).then(new Answer<SeekableByteChannel>() {
        @Override/*  www.  j  av  a  2 s  .c  om*/
        public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable {
            return FileChannel.open(Files.createTempFile("channel-", ".tmp"), StandardOpenOption.CREATE,
                    StandardOpenOption.DELETE_ON_CLOSE);
        }
    });

    // Any request for expansion returns a list containing the original GcsPath
    // This is required to pass validation that occurs in TextIO during apply()
    Mockito.when(mockGcsUtil.expand(Mockito.any(GcsPath.class))).then(new Answer<List<GcsPath>>() {
        @Override
        public List<GcsPath> answer(InvocationOnMock invocation) throws Throwable {
            return ImmutableList.of((GcsPath) invocation.getArguments()[0]);
        }
    });

    return mockGcsUtil;
}

From source file:net.dv8tion.jda.core.utils.SimpleLog.java

private static void logToFiles(String msg, Level level) {
    Set<File> files = collectFiles(level);
    for (File file : files) {
        try {//from w  ww  .  java  2  s  .co m
            Files.write(file.toPath(), (msg + '\n').getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
            //                JDAImpl.LOG.fatal("Could not write log to logFile...");
            //                JDAImpl.LOG.log(e);
        }
    }
}

From source file:edu.cmu.tetrad.cli.search.FgsDiscrete.java

private static void writeOutGraphML(Graph graph, Path outputFile) {
    if (graph == null) {
        return;//ww  w .java2 s .  com
    }

    try (PrintStream graphWriter = new PrintStream(
            new BufferedOutputStream(Files.newOutputStream(outputFile, StandardOpenOption.CREATE)))) {
        String fileName = outputFile.getFileName().toString();

        String msg = String.format("Writing out GraphML file '%s'.", fileName);
        System.out.printf("%s: %s%n", DateTime.printNow(), msg);
        LOGGER.info(msg);
        XmlPrint.printPretty(GraphmlSerializer.serialize(graph, outputPrefix), graphWriter);
        msg = String.format("Finished writing out GraphML file '%s'.", fileName);
        System.out.printf("%s: %s%n", DateTime.printNow(), msg);
        LOGGER.info(msg);
    } catch (Throwable throwable) {
        String errMsg = String.format("Failed when writting out GraphML file '%s'.",
                outputFile.getFileName().toString());
        System.err.println(errMsg);
        LOGGER.error(errMsg, throwable);
    }
}

From source file:gov.vha.isaac.rf2.filter.RF2Filter.java

@Override
public void execute() throws MojoExecutionException {
    if (!inputDirectory.exists() || !inputDirectory.isDirectory()) {
        throw new MojoExecutionException("Path doesn't exist or isn't a folder: " + inputDirectory);
    }/*  w  ww .  ja v  a2  s.c  o  m*/

    if (module == null) {
        throw new MojoExecutionException("You must provide a module or namespace for filtering");
    }

    moduleStrings_.add(module + "");

    outputDirectory.mkdirs();
    File temp = new File(outputDirectory, inputDirectory.getName());
    temp.mkdirs();

    Path source = inputDirectory.toPath();
    Path target = temp.toPath();
    try {
        getLog().info("Reading from " + inputDirectory.getAbsolutePath());
        getLog().info("Writing to " + outputDirectory.getCanonicalPath());

        summary_.append("This content was filtered by an RF2 filter tool.  The parameters were module: "
                + module + " software version: " + converterVersion);
        summary_.append("\r\n\r\n");

        getLog().info("Checking for nested child modules");

        //look in sct2_Relationship_ files, find anything where the 6th column (destinationId) is the 
        //starting module ID concept - and add that sourceId (5th column) to our list of modules to extract
        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toFile().getName().startsWith("sct2_Relationship_")) {
                    //don't look for quotes, the data is bad, and has floating instances of '"' all by itself
                    CSVReader csvReader = new CSVReader(
                            new InputStreamReader(new FileInputStream(file.toFile())), '\t',
                            CSVParser.NULL_CHARACTER);
                    String[] line = csvReader.readNext();
                    if (!line[4].equals("sourceId") || !line[5].equals("destinationId")) {
                        csvReader.close();
                        throw new IOException("Unexpected error looking for nested modules");
                    }
                    line = csvReader.readNext();
                    while (line != null) {
                        if (line[5].equals(moduleStrings_.get(0))) {
                            moduleStrings_.add(line[4]);
                        }
                        line = csvReader.readNext();
                    }
                    csvReader.close();
                }
                return FileVisitResult.CONTINUE;
            }
        });

        log("Full module list (including detected nested modules: "
                + Arrays.toString(moduleStrings_.toArray(new String[moduleStrings_.size()])));

        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetdir = target.resolve(source.relativize(dir));
                try {
                    //this just creates the sub-directory in the target
                    Files.copy(dir, targetdir);
                } catch (FileAlreadyExistsException e) {
                    if (!Files.isDirectory(targetdir))
                        throw e;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                handleFile(file, target.resolve(source.relativize(file)));
                return FileVisitResult.CONTINUE;
            }
        });

        Files.write(new File(temp, "FilterInfo.txt").toPath(), summary_.toString().getBytes(),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
        throw new MojoExecutionException("Failure", e);
    }

    getLog().info("Filter Complete");

}

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

@Test
public void testClassifyFileContentsAsStreamDescClient() throws Exception {
    ServiceDescriptor temp = ServicesCatalog.getItem("news-classifier");
    S4ServiceClient client = new S4ServiceClient(temp, testApiKeyId, testApiKeyPass);
    serializationFormat = ResponseFormat.JSON;
    File f = new File("test-file");
    try {// w w  w .  jav  a 2  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);

        InputStream result = client.annotateFileContentsAsStream(f, Charset.forName("UTF-8"),
                SupportedMimeType.PLAINTEXT, serializationFormat);
        StringWriter writer = new StringWriter();
        IOUtils.copy(result, writer, Charset.forName("UTF-8"));

        assertTrue(writer.toString().contains("category"));
        assertTrue(writer.toString().contains("allScores"));
    } finally {
        f.delete();
    }
}

From source file:org.deeplearning4j.examples.multigpu.video.VideoGenerator.java

public static void generateVideoData(String outputFolder, String filePrefix, int nVideos, int nFrames,
        int width, int height, int numShapesPerVideo, boolean backgroundNoise, int numDistractorsPerFrame,
        long seed) throws Exception {
    Random r = new Random(seed);

    for (int i = 0; i < nVideos; i++) {
        String videoPath = FilenameUtils.concat(outputFolder, filePrefix + "_" + i + ".mp4");
        String labelsPath = FilenameUtils.concat(outputFolder, filePrefix + "_" + i + ".txt");
        int[] labels = generateVideo(videoPath, nFrames, width, height, numShapesPerVideo, r, backgroundNoise,
                numDistractorsPerFrame);

        //Write labels to text file
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < labels.length; j++) {
            sb.append(labels[j]);// www  .j a  va 2  s.  c o m
            if (j != labels.length - 1)
                sb.append("\n");
        }
        Files.write(Paths.get(labelsPath), sb.toString().getBytes("utf-8"), StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING);
    }
}

From source file:at.tfr.securefs.xnio.MessageHandlerImpl.java

@Override
public void handleMessage(String json, MessageSender messageSender) throws IOException {

    log.debug("handleMessage: " + json);
    final Message message = objectMapper.readValue(json, Message.class);

    Path path = configuration.getBasePath().resolve(message.getPath());
    if (!path.relativize(configuration.getBasePath()).toString().equals("..")) {
        throw new SecurityException("invalid path spec: " + message.getPath());
    }//from w  ww.j  a  v a  2s .co  m

    try {
        final String uniqueKey = message.getUniqueKey();
        // find the Channel for this data stream:
        StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>> info = activeStreams.getStreams()
                .get(uniqueKey);

        if (message.getType() == MessageType.OPEN && info != null) {
            log.warn("illegal state on Open stream: " + message);
            IoUtils.safeClose(info.getStream().getRightSide());
            messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
        }

        switch (message.getType()) {
        case ERROR:
            log.info("error from Client: " + json);
        case CLOSE: {
            if (info != null) {
                IoUtils.safeClose(info.getStream().getRightSide());
            }
        }
            break;

        case OPEN: {
            switch (message.getSubType()) {
            case READ: {
                final InputStream is = Files.newInputStream(path, StandardOpenOption.READ);
                final InputStream cis = new CipherInputStream(is, getCipher(message, Cipher.DECRYPT_MODE));

                final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker
                        .createHalfDuplexPipe();
                pipe.getLeftSide().getReadSetter().set(new SecureChannelWriterBase(message) {
                    @Override
                    protected void write(Message message) {
                        try {
                            messageSender.send(message);
                        } catch (Exception e) {
                            log.warn("cannot write message=" + message + " : " + e, e);
                        }
                    }
                });
                pipe.getLeftSide().getCloseSetter().set(new ChannelListener<StreamSourceChannel>() {

                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        activeStreams.getStreams().remove(uniqueKey);
                        messageSender.send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey));
                    }
                });
                pipe.getRightSide().getWriteSetter().set(new ChannelListener<StreamSinkChannel>() {
                    private byte[] bytes = new byte[Constants.BUFFER_SIZE];

                    @Override
                    public void handleEvent(StreamSinkChannel channel) {
                        try {
                            int count = 0;
                            while ((count = cis.read(bytes, 0, bytes.length)) > 0) {
                                if (count > 0) {
                                    Channels.writeBlocking(pipe.getRightSide(),
                                            ByteBuffer.wrap(bytes, 0, count));
                                }
                                if (count < 0) {
                                    pipe.getRightSide().close();
                                } else {
                                    channel.resumeWrites();
                                }
                            }
                        } catch (Exception e) {
                            log.warn("cannot read from cypher: " + e, e);
                            IoUtils.safeClose(channel);
                        }
                    }
                });

                activeStreams.getStreams().put(uniqueKey,
                        new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe,
                                message.getPath()));

                // start sending data:
                pipe.getLeftSide().resumeReads();
                pipe.getRightSide().resumeWrites();
            }
                break;

            case WRITE: {
                Files.createDirectories(path.getParent());
                OutputStream os = Files.newOutputStream(path, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
                OutputStream cos = new CipherOutputStream(os, getCipher(message, Cipher.ENCRYPT_MODE));

                ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker.createHalfDuplexPipe();

                pipe.getLeftSide().getReadSetter().set(new SecureChannelReaderBase() {

                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        readChannel(message, cos, pipe, channel);
                    }
                });

                pipe.getLeftSide().getCloseSetter().set(new SecureChannelReaderBase() {
                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        try {
                            cos.close();
                            activeStreams.getStreams().remove(pipe.toString());
                            messageSender
                                    .send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey));
                            log.info("closed channel: " + pipe.toString());
                        } catch (IOException e) {
                            log.warn("cannot close stream: message=" + message + " : " + e, e);
                        }
                    }
                });
                activeStreams.getStreams().put(uniqueKey,
                        new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe,
                                message.getPath()));

                // start receiving data:
                pipe.getLeftSide().resumeReads();
            }
                break;

            default:
                messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
                break;

            }
        }
            break;

        case DATA: {
            if (info != null) {
                Channels.writeBlocking(info.getStream().getRightSide(), ByteBuffer.wrap(message.getBytes()));
            } else {
                messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
            }
        }
            break;
        }

    } catch (IOException e) {
        log.warn("cannot handle message: " + message + " : " + e, e);
        throw e;
    } catch (Exception e) {
        log.warn("cannot handle message: " + message + " : " + e, e);
        throw new IOException("cannot handle message: " + message + " : " + e, e);
    }
}

From source file:sonicScream.services.SettingsService.java

/**
 *Serializes all current settings objects out to disk, to the specified directory, 
 * relative to the current directory. A folder separator is automatically 
 * appended to the passed string.//from w  w w.ja va  2  s  . c  o  m
 * @param pathToWriteTo The name, or relative path of the folder to write to, without a trailing slash.
 */
public void saveSettings(String pathToWriteTo) {
    if (pathToWriteTo.length() > 2
            && !(pathToWriteTo.charAt(pathToWriteTo.length() - 1) == File.separatorChar)) {
        pathToWriteTo = pathToWriteTo.concat(File.separator);
    }
    try {
        JAXBContext context = JAXBContext.newInstance(SettingsMapWrapper.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Path settingsFile = Paths.get(pathToWriteTo, Constants.SETTINGS_FILE_NAME);
        try (BufferedWriter bw = Files.newBufferedWriter(settingsFile, StandardOpenOption.CREATE)) {
            SettingsMapWrapper wrapper = new SettingsMapWrapper();
            wrapper.setSettingsMap(_settingsDictionary);
            m.marshal(wrapper, bw);
        } catch (IOException ex) {
            System.err.println("Failed to write out " + Constants.SETTINGS_FILE_NAME);
        }

        context = JAXBContext.newInstance(CRCsMapWrapper.class);
        m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Path crcFile = Paths.get(pathToWriteTo, Constants.CRC_CACHE_FILE_NAME);
        try (BufferedWriter bw = Files.newBufferedWriter(crcFile, StandardOpenOption.CREATE)) {
            CRCsMapWrapper wrapper = new CRCsMapWrapper();
            wrapper.setCRCsMap(_crcDictionary);
            m.marshal(wrapper, bw);
        } catch (IOException ex) {
            System.err.println("Failed to write out " + Constants.CRC_CACHE_FILE_NAME);
        }

        context = JAXBContext.newInstance(Profile.class);
        m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        for (Profile profile : _profileList) {
            try {
                Files.createDirectories(Paths.get(pathToWriteTo, Constants.PROFILES_DIRECTORY, File.separator,
                        profile.getProfileName()));
            } catch (IOException ex) {
                //TODO: Tell the user
                ex.printStackTrace();
                break;
            }
            Path profilePath = Paths.get(pathToWriteTo, Constants.PROFILES_DIRECTORY, File.separator,
                    profile.getProfileName(), File.separator,
                    profile.getProfileName() + "_" + Constants.PROFILE_FILE_SUFFIX);
            try (BufferedWriter bw = Files.newBufferedWriter(profilePath)) {
                m.marshal(profile, bw);
            } catch (IOException ex) {
                System.err.printf("\nFailed to write out profile: %s " + ex.getMessage());
            }
        }
    } catch (JAXBException ex) {
        //TODO: Error message
        ex.printStackTrace();
    }

}