Example usage for java.nio.file Files write

List of usage examples for java.nio.file Files write

Introduction

In this page you can find the example usage for java.nio.file Files write.

Prototype

public static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
        throws IOException 

Source Link

Document

Write lines of text to a file.

Usage

From source file:it.polimi.diceH2020.launcher.utility.FileUtility.java

public @NotNull File createTempZip(@NotNull Map<String, String> inputFiles) throws IOException {
    File folder = Files.createTempDirectory(settings.getWorkingDirectory().toPath(), null).toFile();
    policy.markForDeletion(folder);/* w w w .j a  va2  s .com*/

    List<File> tempFiles = new LinkedList<>();
    for (Map.Entry<String, String> entry : inputFiles.entrySet()) {
        File tmp = new File(folder, entry.getKey());
        if (tmp.getParentFile().mkdirs() || tmp.getParentFile().isDirectory()) {
            tempFiles.add(tmp);
            Files.write(tmp.toPath(), Compressor.decompress(entry.getValue()).getBytes(),
                    StandardOpenOption.CREATE_NEW);
        } else
            throw new IOException("could not prepare directory structure for ZIP file");
    }

    String fileName = String.format("%s.zip", folder.getName());
    File zip = new File(settings.getWorkingDirectory(), fileName);
    policy.markForDeletion(zip);
    zipFolder(folder, zip);

    tempFiles.forEach(policy::delete);
    policy.delete(folder);

    return zip;
}

From source file:glass.Plugins.ServerLogPlugin.java

/**
 * @param args the command line arguments
 *//*from  w  ww. j  ava 2 s .  com*/
@Override
public String processFile(String path) {

    //code to create/cleanup work directory 
    String output_folder = "work/ServerLogPlugin/";
    cleanWorkDir(output_folder);

    try {
        FileUtils.copyFile(new File(GUI.toolPath + "configFiles\\ServerLogConfigFiles\\temperature_config.txt"),
                new File(output_folder + "temperature_config.txt"));//copy config files to dest
        FileUtils.copyFile(new File(GUI.toolPath + "configFiles\\ServerLogConfigFiles\\cpu_config.txt"),
                new File(output_folder + "cpu_config.txt"));//copy config files to dest
        FileUtils.copyFile(new File(GUI.toolPath + "configFiles\\ServerLogConfigFiles\\power_config.txt"),
                new File(output_folder + "power_config.txt"));//copy config files to dest
        FileUtils.copyFile(new File(GUI.toolPath + "configFiles\\ServerLogConfigFiles\\dma_config.txt"),
                new File(output_folder + "dma_config.txt"));//copy config files to dest

        //FileUtils.
        List<String> lines = Files.readAllLines(Paths.get(path), Charset.defaultCharset());
        double xValues[] = new double[lines.size()];

        double yValues1[] = new double[lines.size()];
        double yValues2[] = new double[lines.size()];
        double yValues3[] = new double[lines.size()];
        double yValues4[] = new double[lines.size()];

        ArrayList<String> lines_out1 = new ArrayList<>();
        ArrayList<String> lines_out2 = new ArrayList<>();
        ArrayList<String> lines_out3 = new ArrayList<>();
        ArrayList<String> lines_out4 = new ArrayList<>();

        for (int i = 1; i < lines.size(); i++) {
            String[] line_cloumn = lines.get(i).split(",");
            xValues[i] = i;

            yValues1[i] = Double.parseDouble(line_cloumn[49]);
            yValues2[i] = Double.parseDouble(line_cloumn[1]);
            yValues3[i] = Double.parseDouble(line_cloumn[48]);
            yValues4[i] = Double.parseDouble(line_cloumn[11]);

            lines_out1.add("" + xValues[i] + "," + yValues1[i]);
            lines_out2.add("" + xValues[i] + "," + yValues2[i]);
            lines_out3.add("" + xValues[i] + "," + yValues3[i]);
            lines_out4.add("" + xValues[i] + "," + yValues4[i]);
        }

        Files.write(Paths.get(output_folder + "temperature" + ".txt"), lines_out1, Charset.defaultCharset());
        Files.write(Paths.get(output_folder + "cpu" + ".txt"), lines_out2, Charset.defaultCharset());
        Files.write(Paths.get(output_folder + "power" + ".txt"), lines_out3, Charset.defaultCharset());
        Files.write(Paths.get(output_folder + "dma" + ".txt"), lines_out4, Charset.defaultCharset());

        return output_folder;
    } catch (Exception ex) {
        Logger.getLogger(ServerLogPlugin.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
        return "";
    }
}

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 w w . j av  a2 s  .c o  m
@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:org.fim.tooling.RepositoryTool.java

public void createFimIgnore(Path directory, String content) throws IOException {
    Path file = directory.resolve(".fimignore");
    if (Files.exists(file)) {
        Files.delete(file);/*  ww w .  ja v  a  2 s .  co  m*/
    }
    Files.write(file, content.getBytes(), CREATE);
}

From source file:org.apache.storm.security.auth.AutoSSLTest.java

@Test
public void testpopulateCredentials() throws Exception {
    File temp = File.createTempFile("tmp-autossl-test", ".txt");
    temp.deleteOnExit();//from  www  .j a  v a  2 s  . co  m
    List<String> lines = Arrays.asList("The first line", "The second line");
    Files.write(temp.toPath(), lines, Charset.forName("UTF-8"));
    File baseDir = null;
    try {
        baseDir = new File("/tmp/autossl-test-" + UUID.randomUUID());
        if (!baseDir.mkdir()) {
            throw new IOException("failed to create base directory");
        }
        AutoSSL assl = new TestAutoSSL(baseDir.getPath());

        LOG.debug("base dir is; " + baseDir);
        Map sslconf = new HashMap();

        sslconf.put(AutoSSL.SSL_FILES_CONF, temp.getPath());
        assl.prepare(sslconf);
        Collection<String> sslFiles = assl.getSSLFilesFromConf(sslconf);

        Map<String, String> creds = new HashMap();
        assl.populateCredentials(creds);
        assertTrue(creds.containsKey(temp.getName()));

        Subject unusedSubject = new Subject();
        assl.populateSubject(unusedSubject, creds);
        String[] outputFiles = baseDir.list();
        assertEquals(1, outputFiles.length);

        // compare contents of files
        if (outputFiles.length > 0) {
            List<String> linesWritten = FileUtils.readLines(new File(baseDir, outputFiles[0]),
                    Charset.forName("UTF-8"));
            for (String l : linesWritten) {
                assertTrue(lines.contains(l));
            }
        }
    } finally {
        if (baseDir != null) {
            FileUtils.deleteDirectory(baseDir);
        }
    }
}

From source file:org.fim.internal.FimIgnoreManagerTest.java

@Test
public void weCanLoadCorrectlyAFimIgnore() throws IOException {
    FimIgnore fimIgnore = cut.loadFimIgnore(rootDir);
    assertThat(fimIgnore.getFilesToIgnoreLocally().size()).isEqualTo(0);
    assertThat(fimIgnore.getFilesToIgnoreInAllDirectories().size()).isEqualTo(0);

    String fileContent = "**/*.mp3\n" + "*.mp4\n" + "**/.git\n" + "foo\n" + "**/bar";
    Files.write(rootDir.resolve(".fimignore"), fileContent.getBytes(), CREATE);

    fimIgnore = cut.loadFimIgnore(rootDir);
    assertThat(fimIgnore.getFilesToIgnoreLocally().toString())
            .isEqualTo("[FileToIgnore{fileNamePattern=foo, compiledPattern=^foo$},"
                    + " FileToIgnore{fileNamePattern=*.mp4, compiledPattern=^.*\\.mp4$}]");

    assertThat(fimIgnore.getFilesToIgnoreInAllDirectories().toString())
            .isEqualTo("[FileToIgnore{fileNamePattern=bar, compiledPattern=^bar$},"
                    + " FileToIgnore{fileNamePattern=.git, compiledPattern=^\\.git$},"
                    + " FileToIgnore{fileNamePattern=*.mp3, compiledPattern=^.*\\.mp3$}]");
}

From source file:org.apache.archiva.checksum.ChecksummedFile.java

/**
 * Creates a checksum file of the provided referenceFile.
 *
 * @param checksumAlgorithm the hash to use.
 * @return the checksum File that was created.
 * @throws IOException if there was a problem either reading the referenceFile, or writing the checksum file.
 *//*from w  w  w .j a  va 2  s  .c  o m*/
public File createChecksum(ChecksumAlgorithm checksumAlgorithm) throws IOException {
    File checksumFile = new File(referenceFile.getAbsolutePath() + "." + checksumAlgorithm.getExt());
    Files.deleteIfExists(checksumFile.toPath());
    String checksum = calculateChecksum(checksumAlgorithm);
    Files.write(checksumFile.toPath(), //
            (checksum + "  " + referenceFile.getName()).getBytes(), //
            StandardOpenOption.CREATE_NEW);
    return checksumFile;
}

From source file:org.geppetto.persistence.s3.S3Manager.java

public void saveTextToS3(String text, String path) throws IOException {
    File file = File.createTempFile("file", "");
    Files.write(file.toPath(), text.getBytes(), StandardOpenOption.APPEND);
    saveFileToS3(file, path);/*from w  w  w. ja  va2s. c  om*/
}

From source file:org.fim.command.RemoveDuplicatesCommandTest.java

@Test
public void weCanRemoveDuplicates() throws Exception {
    Context context = tool.createContext(hashAll, false);

    tool.createASetOfFiles(5);//from w  ww  .ja v  a 2 s . c o m

    State state = (State) initCommand.execute(context);
    assertThat(state.getModificationCounts().getAdded()).isEqualTo(5);

    // Setup the context to use a master directory
    context.setCurrentDirectory(rootDirCopy);
    context.setMasterFimRepositoryDir(rootDir.toString());
    long totalFilesRemoved = (long) removeDuplicatesCommand.execute(context);
    assertThat(totalFilesRemoved).isEqualTo(0);

    Files.copy(rootDir.resolve("file01"), rootDirCopy.resolve("file01"));
    Files.copy(rootDir.resolve("file02"), rootDirCopy.resolve("file02"));
    Files.copy(rootDir.resolve("file03"), rootDirCopy.resolve("file03"));
    Files.copy(rootDir.resolve("file04"), rootDirCopy.resolve("file04"));
    Files.copy(rootDir.resolve("file05"), rootDirCopy.resolve("file05"));

    // Modify file03
    Files.write(rootDirCopy.resolve("file03"), "appended content".getBytes(), APPEND);

    totalFilesRemoved = (long) removeDuplicatesCommand.execute(context);
    // Only 4 files are duplicated
    assertThat(totalFilesRemoved).isEqualTo(4);
}

From source file:net.kemitix.checkstyle.ruleset.builder.CheckstyleWriter.java

private void writeCheckstyleFile(@NonNull final RuleLevel ruleLevel) {
    val xmlFile = outputProperties.getDirectory().resolve(outputProperties.getRulesetFiles().get(ruleLevel));
    val checkerRules = rulesProperties.getRules().stream().filter(Rule::isEnabled)
            .filter(rule -> RuleParent.CHECKER.equals(rule.getParent()))
            .filter(rule -> ruleLevel.compareTo(rule.getLevel()) >= 0).map(this::formatRuleAsModule)
            .collect(Collectors.joining(NEWLINE));
    val treeWalkerRules = rulesProperties.getRules().stream().filter(Rule::isEnabled)
            .filter(rule -> RuleParent.TREEWALKER.equals(rule.getParent()))
            .filter(rule -> ruleLevel.compareTo(rule.getLevel()) >= 0).map(this::formatRuleAsModule)
            .collect(Collectors.joining(NEWLINE));
    try {//w w  w  .j a v  a 2s . c om
        val checkstyleXmlTemplate = templateProperties.getCheckstyleXml();
        if (checkstyleXmlTemplate.toFile().exists()) {
            val bytes = Files.readAllBytes(checkstyleXmlTemplate);
            val template = new String(bytes, StandardCharsets.UTF_8);
            val output = Arrays.asList(String.format(template, checkerRules, treeWalkerRules).split(NEWLINE));
            log.info("Writing xmlFile: {}", xmlFile);
            Files.write(xmlFile, output, StandardCharsets.UTF_8);
        } else {
            throw new IOException("Missing template: " + checkstyleXmlTemplate.toString());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}