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:Main.java

public static void main(String[] args) {
    Path myText_path = Paths.get("C:/tutorial/wiki", "wiki.txt");
    Charset charset = Charset.forName("UTF-8");
    ArrayList<String> lines = new ArrayList<>();
    lines.add("\n");
    lines.add("tutorial");

    try {//from  w  ww. ja v  a 2 s . c  o  m
        Files.write(myText_path, lines, charset, StandardOpenOption.APPEND);
    } catch (IOException e) {
        System.err.println(e);
    }

}

From source file:nls.formacao.matriculador.descarregador.DesCarregadorFicheiro.java

@Override
public void escrever(String info) {
    String nome = Utils.obtemNomeFicheiro("txt");
    try {//from w w  w. j  a v a  2  s  .com
        Path p = Paths.get(nome);
        Files.write(p, info.getBytes(Charset.forName("UTF-8")), StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);
    } catch (IOException ex) {
        LOG.error("Erro a descarregar registos para o ecr.", ex);
        System.err.println("Erro a descarregar informao para o ecr.");
    }
    System.out.println(String.format("Criado o ficheiro %s.", nome));
}

From source file:nls.formacao.matriculador.descarregador.DesCarregadorFicheiro.java

@Override
public void escrever(Registo[] info) {
    String nomeFicheiro = Utils.obtemNomeFicheiro("txt");
    for (Registo registo : info) {
        if (registo == null) {
            continue;
        }//from w  w w  . ja  v  a2s.c om
        try {
            Path p = Paths.get(nomeFicheiro);
            Files.write(p, registo.prettyPrint().getBytes(Charset.forName("UTF-8")), StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);
        } catch (IOException ex) {
            LOG.error("Erro a descarregar registo para o ecr.", ex);
            System.err.println("Erro a descarregar registo para o ficheiro.");
        }
    }
    LOG.info(String.format("Informao descarregada com sucesso para o ficheiro '%s'", nomeFicheiro));
    System.out.println(String.format("Criado o ficheiro %s.", nomeFicheiro));
}

From source file:org.wso2.msf4j.perftest.echo.springboot.EchoService.java

@RequestMapping("/EchoService/fileecho")
@ResponseBody/*from   w w  w.ja  va2s.  c  o m*/
public String fileWrite(@RequestBody String body) throws InterruptedException, IOException {
    String returnStr = "";
    java.nio.file.Path tempfile = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    Files.write(tempfile, body.getBytes(Charset.defaultCharset()), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);
    returnStr = new String(Files.readAllBytes(tempfile), Charset.defaultCharset());
    Files.delete(tempfile);
    return returnStr;
}

From source file:com.scaniatv.LangFileUpdater.java

/**
 * Method that updates a custom lang file.
 * //from ww  w  . j av  a2s . c o m
 * @param stringArray 
 * @param langFile 
 */
public static void updateCustomLang(String stringArray, String langFile) {
    final StringBuilder sb = new StringBuilder();
    final JSONArray array = new JSONArray(stringArray);

    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);

        sb.append("$.lang.register('" + obj.getString("id") + "', '"
                + sanitizeResponse(obj.getString("response")) + "');\n");
    }

    try {
        langFile = CUSTOM_LANG_ROOT + langFile.replaceAll("\\\\", "/");

        File file = new File(langFile);
        boolean exists = true;

        // Make sure the folder exists.
        if (!file.getParentFile().isDirectory()) {
            file.getParentFile().mkdirs();
        }

        // This is used if we need to load the script or not.
        if (!file.exists()) {
            exists = false;
        }

        // Write the data.
        Files.write(Paths.get(langFile), sb.toString().getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

        // If the script doesn't exist, load it.
        if (!exists) {
            ScriptManager.loadScript(file);
        }
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }
}

From source file:net.javacrumbs.codecamp.common.CsvFileLogger.java

@Override
public void addMessage(Message message) {
    try {//from  ww w . j  av  a 2s  .co  m
        String newRow = CSVFormat.RFC4180.format(message.getSeverity(), message.getMessage(),
                message.getTime());
        Files.write(file.toPath(), singletonList(newRow), APPEND, CREATE);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:net.javacrumbs.codecamp.boot.common.CsvFileLogger.java

@Override
@CacheEvict(value = "messages", key = "'messages'")
public void addMessage(Message message) {
    try {/*from www  . j  a  v  a 2  s.c o m*/
        String newRow = CSVFormat.RFC4180.format(message.getSeverity(), message.getText(), message.getTime());
        Files.write(file.toPath(), singletonList(newRow), APPEND, CREATE);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.google.demo.translate.Translator.java

private static void translate(List<String> texts) throws IOException {
    List<String> lines = new ArrayList<>();
    for (String text : texts) {
        lines.add(postTranslationParser(text));
    }//  ww  w.j  a va 2s .  com

    for (String target : targets) {
        List<Translation> translations = translate.translate(texts, TranslateOption.sourceLanguage(source),
                TranslateOption.targetLanguage(target), TranslateOption.model("nmt"));

        List<String> results = new ArrayList<>();
        for (int i = 0; i < lines.size(); i++) {
            String translation = postTranslationParser(translations.get(i).getTranslatedText());
            results.add(String.join(";", lines.get(i), translation));
        }

        lines = results;
    }

    Files.write(output, lines, UTF_8, APPEND);
}

From source file:com.willwinder.universalgcodesender.model.GUIBackendPreprocessorTest.java

/**
 * Test of preprocessAndExportToFile method, of class GUIBackend.
 *//* w  w  w.ja  v  a2  s  .co m*/
@Test
public void testRegularPreprocessAndExportToFile() throws Exception {
    System.out.println("regularPreprocessAndExportToFile");
    GUIBackend backend = new GUIBackend();
    GcodeParser gcp = new GcodeParser();
    // Double all the commands that go in.
    gcp.addCommandProcessor(commandDoubler);
    gcp.addCommandProcessor(new CommentProcessor());

    // Create input file, comment-only line shouldn't be processed twice.
    List<String> lines = Arrays.asList("line one", "; comment", "line two");
    Files.write(inputFile, lines, Charset.defaultCharset(), StandardOpenOption.WRITE);

    backend.preprocessAndExportToFile(gcp, inputFile.toFile(), outputFile.toFile());

    List<String> expectedResults = Arrays.asList("line one", "line one", "", "line two", "line two");

    try (GcodeStreamReader reader = new GcodeStreamReader(outputFile.toFile())) {
        Assert.assertEquals(expectedResults.size(), reader.getNumRows());

        for (String expected : expectedResults) {
            Assert.assertEquals(expected, reader.getNextCommand().getCommandString());
        }
    }
}