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.appsolve.padelcampus.utils.HtmlResourceUtil.java

private void replaceVariables(ServletContext context, List<CssAttribute> cssAttributes, String FILE_NAME,
        File destDir) throws IOException {
    InputStream lessIs = context.getResourceAsStream(FILE_NAME);
    Path outputPath = new File(destDir, FILE_NAME).toPath();
    String content = IOUtils.toString(lessIs, Constants.UTF8);
    for (CssAttribute attribute : cssAttributes) {
        if (!StringUtils.isEmpty(attribute.getCssValue())) {
            content = content.replaceAll(attribute.getCssDefaultValue(), attribute.getCssValue());
        }/*  w  w w .  j  a va  2 s  .c o  m*/
    }

    //overwrite variables.less in data directory
    if (!Files.exists(outputPath)) {
        if (!Files.exists(outputPath.getParent())) {
            Files.createDirectory(outputPath.getParent());
        }
        Files.createFile(outputPath);
    }
    Files.write(outputPath, content.getBytes(Constants.UTF8), StandardOpenOption.CREATE,
            StandardOpenOption.WRITE);
}

From source file:net.sf.taverna.t2.commandline.data.InputsHandler.java

private void setValue(Path port, Object userInput) throws IOException {
    if (userInput instanceof File) {
        DataBundles.setReference(port, ((File) userInput).toURI());
    } else if (userInput instanceof URL) {
        try {//from   w  w  w .j  av a2s  . c  o  m
            DataBundles.setReference(port, ((URL) userInput).toURI());
        } catch (URISyntaxException e) {
            logger.warn(String.format("Error converting %1$s to URI", userInput), e);
        }
    } else if (userInput instanceof String) {
        DataBundles.setStringValue(port, (String) userInput);
    } else if (userInput instanceof byte[]) {
        Files.write(port, (byte[]) userInput, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
    } else if (userInput instanceof List<?>) {
        DataBundles.createList(port);
        List<?> list = (List<?>) userInput;
        for (Object object : list) {
            setValue(DataBundles.newListItem(port), object);
        }
    } else {
        logger.warn("Unknown input type : " + userInput.getClass().getName());
    }
}

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

@Test
public void testAnnotateFileContentsUrlClient() throws Exception {
    File f = new File("test-file");
    try {//w  w  w. j a v a  2 s.c  om
        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 = apiUrl.annotateFileContents(f, Charset.forName("UTF-8"), documentMimeType);
        assertTrue(result.getText().contains("Barack"));
    } finally {
        f.delete();
    }
}

From source file:org.ballerinalang.containers.docker.impl.DefaultBallerinaDockerClient.java

private String createImageFromSingleConfig(String serviceName, String dockerEnv, String ballerinaConfig,
        boolean isService, String imageName, String imageVersion)
        throws BallerinaDockerClientException, IOException, InterruptedException {

    imageName = getImageName(serviceName, imageName, imageVersion);

    // 1. Create a tmp docker context
    Path tmpDir = prepTempDockerfileContext();

    // 2. Create a .bal file inside context/files
    Path ballerinaFile = Files.createFile(
            Paths.get(tmpDir + File.separator + PATH_FILES + File.separator + serviceName + PATH_BAL_FILE_EXT));

    Files.write(ballerinaFile, ballerinaConfig.getBytes(Charset.defaultCharset()), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);

    // 3. Create a docker image from the temp context
    String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssXX").format(new Date());
    String buildArgs = "{\"" + ENV_SVC_MODE + "\":\"" + String.valueOf(isService) + "\", " + "\""
            + ENV_FILE_MODE + "\":\"true\", \"BUILD_DATE\":\"" + timestamp + "\"}";
    buildImage(dockerEnv, imageName, tmpDir, buildArgs);

    // 4. Cleanup
    cleanupTempDockerfileContext(tmpDir);

    return getImage(imageName, dockerEnv);
}

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

@Test
public void testClassifyFileContentsUrlClient() throws Exception {
    ServiceDescriptor temp = ServicesCatalog.getItem("news-classifier");
    S4ServiceClient client = new S4ServiceClient(temp, testApiKeyId, testApiKeyPass);

    File f = new File("test-file");
    try {/*from   w  w w  . ja v 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);
        ClassifiedDocument result = client.classifyFileContents(f, Charset.forName("UTF-8"), documentMimeType);
        assertNotNull(result.getCategory());
        assertEquals(3, result.getAllScores().size());
    } finally {
        f.delete();
    }
}

From source file:edu.umd.umiacs.clip.tools.io.AllFiles.java

public static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) {
    if (options.length == 0) {
        options = new OpenOption[] { CREATE_NEW };
    }/*from  w ww . j  a va  2s .com*/
    try {
        File parent = path.getParent().toFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        return path.toString().endsWith(".gz") ? GZIPFiles.write(path, lines, UTF_8, options)
                : path.toString().endsWith(".bz2") ? BZIP2Files.write(path, lines, UTF_8, options)
                        : Files.write(path, lines, UTF_8, options);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:api.wiki.WikiGenerator.java

private static void writePage(Path page, String markup) throws IOException {
    Files.createDirectories(page.getParent());
    Files.write(page, markup.getBytes(UTF_8), CREATE, TRUNCATE_EXISTING);
}

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

@Test
public void testClassifyFileContentsAsStreamUrlClient() 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 {/*from  w w w.  j ava2s .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:io.spotnext.maven.mojo.TransformTypesMojo.java

private void trackExecution(String message) throws IllegalStateException {
    if (debug) {// w  w  w.j a  v a 2s  .  c  o  m
        try {
            File tempDir = FileUtils.getTempDirectory();

            Files.write(Paths.get(tempDir.getAbsolutePath(), "transform-classes.log"),
                    (new Date().toString() + ": " + message + "\n").getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (Exception e) {
            throw new IllegalStateException("error", e);
        }
    }
}

From source file:org.eclipse.winery.generators.ia.Generator.java

private void generateJavaFile(File javaService) throws IOException {

    // Generate methods
    StringBuilder sb = new StringBuilder();

    for (TOperation op : this.tinterface.getOperation()) {
        // Annotations
        sb.append("\t@WebMethod\n");
        sb.append("\t@SOAPBinding\n");
        sb.append("\t@Oneway\n");

        // Signatur
        String operationReturn = "void";
        sb.append("\tpublic " + operationReturn + " " + op.getName() + "(\n");

        // Parameter
        boolean first = true;
        if (op.getInputParameters() != null) {
            for (TParameter parameter : op.getInputParameters().getInputParameter()) {
                String parameterName = parameter.getName();

                if (first) {
                    first = false;//from   ww  w . j ava  2s  .c  o  m
                    sb.append("\t\t");
                } else {
                    sb.append(",\n\t\t");
                }

                // Generate @WebParam
                sb.append("@WebParam(name=\"" + parameterName + "\", targetNamespace=\"" + this.namespace
                        + "\") ");

                // Handle required and optional parameters using @XmlElement
                if (parameter.getRequired().equals(TBoolean.YES)) {
                    sb.append("@XmlElement(required=true)");
                } else {
                    sb.append("@XmlElement(required=false)");
                }

                sb.append(" String " + parameterName);
            }
        }
        sb.append("\n\t) {\n");

        // If there are output parameters we generate the respective HashMap
        boolean outputParamsExist = (op.getOutputParameters() != null)
                && (!op.getOutputParameters().getOutputParameter().isEmpty());
        if (outputParamsExist) {
            sb.append("\t\t// This HashMap holds the return parameters of this operation.\n");
            sb.append("\t\tfinal HashMap<String,String> returnParameters = new HashMap<String, String>();\n\n");
        }

        sb.append("\t\t// TODO: Implement your operation here.\n");

        // Generate code to set output parameters
        if (outputParamsExist) {
            for (TParameter outputParam : op.getOutputParameters().getOutputParameter()) {
                sb.append("\n\n\t\t// Output Parameter '" + outputParam.getName() + "' ");
                if (outputParam.getRequired().equals(TBoolean.YES)) {
                    sb.append("(required)");
                } else {
                    sb.append("(optional)");
                }
                sb.append("\n\t\t// TODO: Set " + outputParam.getName() + " parameter here.");
                sb.append(
                        "\n\t\t// Do NOT delete the next line of code. Set \"\" as value if you want to return nothing or an empty result!");
                sb.append("\n\t\treturnParameters.put(\"" + outputParam.getName() + "\", \"TODO\");");
            }
            sb.append("\n\n\t\tsendResponse(returnParameters);\n");
        }

        sb.append("\t}\n\n");
    }

    // Read file and replace placeholders
    Charset cs = Charset.defaultCharset();
    List<String> lines = new ArrayList<>();
    for (String line : Files.readAllLines(javaService.toPath(), cs)) {
        // Replace web service method
        line = line.replaceAll(Generator.PLACEHOLDER_GENERATED_WEBSERVICE_METHODS, sb.toString());
        lines.add(line);
    }

    // Write file
    OpenOption[] options = new OpenOption[] { StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING };
    Files.write(javaService.toPath(), lines, cs, options);
}