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, Charset cs, OpenOption... options)
        throws IOException 

Source Link

Document

Write lines of text to a file.

Usage

From source file:de.tuberlin.uebb.jbop.access.ClassAccessor.java

/**
 * Stores a classfile for the given Classdescriptor.
 * /*  w  ww .  ja va  2 s  .  co  m*/
 * The Class for the File could be loaded with the ClassLoader proposed by this
 * Class ({@link #getClassloader()}) or any suitable ClassLoader using the returned
 * Path of the Classfile.
 * 
 * @param classDescriptor
 *          the class descriptor
 * @return the path of the written File
 * @throws JBOPClassException
 *           the jBOP class exception
 */
public static Path store(final ClassDescriptor classDescriptor) throws JBOPClassException {

    final Path packageDir = Paths.get(TMP_DIR.toString(), classDescriptor.getPackageDir());
    final Path classFile = Paths.get(packageDir.toString(), classDescriptor.getSimpleName() + ".class");
    try {
        Files.createDirectories(packageDir);
        Files.write(classFile, classDescriptor.getClassData(), StandardOpenOption.CREATE,
                StandardOpenOption.WRITE);
        classDescriptor.setFile(classFile.toString());
        return classFile;
    } catch (final IOException e) {
        throw new JBOPClassException(
                "Data of Class " + classDescriptor.getName() + " could not be written to file.", e);
    }
}

From source file:org.apache.druid.segment.loading.LocalDataSegmentPusher.java

private DataSegment createDescriptorFile(DataSegment segment, File dest) throws IOException {
    log.info("Creating descriptor file at[%s]", dest);
    // Avoid using Guava in DataSegmentPushers because they might be used with very diverse Guava versions in
    // runtime, and because Guava deletes methods over time, that causes incompatibilities.
    Files.write(dest.toPath(), jsonMapper.writeValueAsBytes(segment), StandardOpenOption.CREATE,
            StandardOpenOption.SYNC);

    return segment;
}

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

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

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

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

    final ByteBuffer targetFileKey = randomFileKey();
    fileContext.targetKeySupplier(() -> targetFileKey);

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

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

    fileBack.operate(fileContext);
}

From source file:com.streamsets.datacollector.publicrestapi.CredentialsDeploymentResource.java

private void handleKerberos(CredentialsBeanJson credentialsBeanJson) throws IOException {
    if (!StringUtils.isEmpty(credentialsBeanJson.getPrincipal())) {
        LOG.info("Kerberos credentials found, deploying..");
        byte[] decodedKeytab = Base64.getDecoder().decode(credentialsBeanJson.getKeytab());
        java.nio.file.Path keytab = Paths.get(runtimeInfo.getConfigDir(), "sdc.keytab");
        Files.write(keytab, decodedKeytab, CREATE, WRITE);
        File sdcProperties = new File(runtimeInfo.getConfigDir(), "sdc.properties");
        Configuration conf = new Configuration();
        try (FileReader reader = new FileReader(sdcProperties)) {
            conf.load(reader);/*from  w w  w  .  ja  va2  s .c om*/
        }
        conf.set("kerberos.client.principal", credentialsBeanJson.getPrincipal());
        conf.set("kerberos.client.enabled", true);
        conf.set("kerberos.client.keytab", "sdc.keytab");
        try (FileWriter writer = new FileWriter(sdcProperties)) {
            conf.save(writer);
        }
        LOG.info("Kerberos credentials deployed.");
    }
}

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

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

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

    final ByteBuffer fileKey = randomFileKey();
    if (current().nextBoolean()) {
        fileContext.sourceKeySupplier(() -> fileKey);
    } else {/* w w w .  j a v  a2  s  .c om*/
        fileContext.targetKeySupplier(() -> 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");
    }

    fileBack.operate(fileContext);
}

From source file:org.apache.metron.dataloads.nonbulk.flatfile.SimpleEnrichmentFlatFileLoaderIntegrationTest.java

@BeforeClass
public static void setup() throws Exception {
    UnitTestHelper.setJavaLoggingLevel(Level.SEVERE);
    Map.Entry<HBaseTestingUtility, Configuration> kv = HBaseUtil.INSTANCE.create(true);
    config = kv.getValue();//w ww .  jav a  2 s  .c  o  m
    testUtil = kv.getKey();
    testTable = testUtil.createTable(Bytes.toBytes(tableName), Bytes.toBytes(cf));
    zookeeperUrl = getZookeeperUrl(config.get("hbase.zookeeper.quorum"),
            testUtil.getZkCluster().getClientPort());
    setupGlobalConfig(zookeeperUrl);

    for (Result r : testTable.getScanner(Bytes.toBytes(cf))) {
        Delete d = new Delete(r.getRow());
        testTable.delete(d);
    }

    if (lineByLineExtractorConfigFile.exists()) {
        lineByLineExtractorConfigFile.delete();
    }
    Files.write(lineByLineExtractorConfigFile.toPath(), lineByLineExtractorConfig.getBytes(),
            StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING);
    if (wholeFileExtractorConfigFile.exists()) {
        wholeFileExtractorConfigFile.delete();
    }
    Files.write(wholeFileExtractorConfigFile.toPath(), wholeFileExtractorConfig.getBytes(),
            StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING);
    if (stellarExtractorConfigFile.exists()) {
        stellarExtractorConfigFile.delete();
    }
    Files.write(stellarExtractorConfigFile.toPath(),
            stellarExtractorConfig.replace("%ZK_QUORUM%", zookeeperUrl).getBytes(),
            StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING);
    if (customLineByLineExtractorConfigFile.exists()) {
        customLineByLineExtractorConfigFile.delete();
    }
    Files.write(
            customLineByLineExtractorConfigFile.toPath(), customLineByLineExtractorConfig
                    .replace("%EXTRACTOR_CLASS%", CSVExtractor.class.getName()).getBytes(),
            StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING);
    if (file1.exists()) {
        file1.delete();
    }
    Files.write(file1.toPath(), "google1.com,1,foo2\n".getBytes(), StandardOpenOption.CREATE_NEW,
            StandardOpenOption.TRUNCATE_EXISTING);
    if (file2.exists()) {
        file2.delete();
    }
    Files.write(file2.toPath(), "google2.com,2,foo2\n".getBytes(), StandardOpenOption.CREATE_NEW,
            StandardOpenOption.TRUNCATE_EXISTING);

    if (multilineFile.exists()) {
        multilineFile.delete();
    }
    if (multilineGzFile.exists()) {
        multilineGzFile.delete();
    }
    if (multilineGzFile.exists()) {
        multilineZipFile.delete();
    }
    PrintWriter[] pws = new PrintWriter[] {};
    try {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(multilineZipFile));
        ZipEntry entry = new ZipEntry("file");
        zos.putNextEntry(entry);
        pws = new PrintWriter[] { new PrintWriter(multilineFile), new PrintWriter(zos),
                new PrintWriter(new GZIPOutputStream(new FileOutputStream(multilineGzFile))) };
        for (int i = 0; i < NUM_LINES; ++i) {
            for (PrintWriter pw : pws) {
                pw.println("google" + i + ".com," + i + ",foo" + i);
            }
        }
    } finally {
        for (PrintWriter pw : pws) {
            pw.close();
        }
    }

}

From source file:com.evolveum.midpoint.model.intest.manual.CsvBackingStore.java

protected void replaceInCsv(String[] data) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath()));
    boolean found = false;
    for (int i = 0; i < lines.size(); i++) {
        String line = lines.get(i);
        String[] cols = line.split(",");
        if (cols[0].matches("\"" + data[0] + "\"")) {
            lines.set(i, formatCsvLine(data));
            found = true;//from   w ww .  ja  v  a2s .co  m
        }
    }
    if (!found) {
        throw new IllegalStateException("Not found in CSV: " + data[0]);
    }
    Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE,
            StandardOpenOption.TRUNCATE_EXISTING);
}

From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java

private String concatenateCss(ServletContext context, Path path, Path outFile)
        throws FileNotFoundException, IOException {
    DirectoryStream<Path> cssFiles = Files.newDirectoryStream(path, "*.css");
    if (Files.exists(outFile)) {
        Files.delete(outFile);//  w  w w. j a va 2 s . c om
    }
    List<Path> sortedFiles = new ArrayList<>();
    for (Path cssFile : cssFiles) {
        sortedFiles.add(cssFile);
    }

    Collections.sort(sortedFiles, new PathByFileNameComparator());

    for (Path cssFile : sortedFiles) {
        Files.write(outFile, Files.readAllBytes(cssFile), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    byte[] cssData;
    if (Files.exists(outFile)) {
        cssData = Files.readAllBytes(outFile);
    } else {
        //read from classpath
        InputStream is = context.getResourceAsStream(ALL_MIN_CSS);
        cssData = IOUtils.toByteArray(is);
    }
    String css = new String(cssData, Constants.UTF8);
    return css;
}

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. ja v  a 2s.c  o  m*/
            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.evolveum.midpoint.model.intest.manual.CsvBackingStore.java

protected void deleteInCsv(String username) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath()));
    Iterator<String> iterator = lines.iterator();
    while (iterator.hasNext()) {
        String line = iterator.next();
        String[] cols = line.split(",");
        if (cols[0].matches("\"" + username + "\"")) {
            iterator.remove();//from   w w w.j  a  v a  2s. c om
        }
    }
    Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE,
            StandardOpenOption.TRUNCATE_EXISTING);
}