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

public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");
    byte[] contents = Files.readAllBytes(path);

    Path newPath = Paths.get("/newUsers.txt");

    Files.write(newPath, contents, StandardOpenOption.CREATE);

}

From source file:Main.java

public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");
    byte[] contents = Files.readAllBytes(path);

    Path newPath = Paths.get("/newUsers.txt");
    byte[] newContents = "aaa".getBytes();
    Files.write(newPath, contents, StandardOpenOption.CREATE);
    Files.write(newPath, newContents, StandardOpenOption.APPEND);
}

From source file:org.eclipse.mylyn.docs.examples.GenerateEPUB.java

public static void main(String[] args) {

    // clean up from last run
    try {//from ww  w .  ja v a 2  s  .  c  o  m
        Files.delete(Paths.get("loremipsum.html"));
        Files.delete(Paths.get("loremipsum.epub"));
    } catch (IOException e1) {
        /* no worries */ }

    try ( // read MarkDown
            FileReader fr = new FileReader("loremipsum.md");
            // and output HTML
            Writer fw = Files.newBufferedWriter(Paths.get("loremipsum.html"), StandardOpenOption.CREATE)) {

        // generate HTML from markdown
        MarkupParser parser = new MarkupParser();
        parser.setMarkupLanguage(new MarkdownLanguage());
        HtmlDocumentBuilder builder = new HtmlDocumentBuilder(fw);
        parser.setBuilder(builder);
        parser.parse(fr, true);

        // convert any inline equations in the HTML into MathML
        String html = new String(Files.readAllBytes(Paths.get("loremipsum.html")));
        StringBuffer sb = new StringBuffer();
        Matcher m = EQUATION.matcher(html);

        // for each equation
        while (m.find()) {
            // replace the LaTeX code with MathML
            m.appendReplacement(sb, laTeX2MathMl(m.group()));
        }
        m.appendTail(sb);

        // EPUB 2.0 can only handle embedded SVG so we find all referenced
        // SVG files and replace the reference with the actual SVG code
        Document parse = Jsoup.parse(sb.toString(), "UTF-8", Parser.xmlParser());

        Elements select = parse.select("img");
        for (Element element : select) {
            String attr = element.attr("src");
            if (attr.endsWith(".svg")) {
                byte[] svg = Files.readAllBytes(Paths.get(attr));
                element.html(new String(svg));
            }
        }

        // write back the modified HTML-file
        Files.write(Paths.get("loremipsum.html"), sb.toString().getBytes(), StandardOpenOption.WRITE);

        // instantiate a new EPUB version 2 publication
        Publication pub = Publication.getVersion2Instance();

        // include referenced resources (default is false)
        pub.setIncludeReferencedResources(true);

        // title and subject is required
        pub.addTitle("EclipseCon Demo");
        pub.addSubject("EclipseCon Demo");

        // generate table of contents (default is true)
        pub.setGenerateToc(true);
        epub.add(pub);

        // add one chapter
        pub.addItem(Paths.get("loremipsum.html").toFile());

        // create the EPUB
        epub.pack(new File("loremipsum.epub"));

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.sastix.cms.server.utils.FileService.java

private String saveFile(String relativePath, byte[] resourceBinary) {
    Path path = Paths.get(volume + relativePath);
    try {/*from  w w  w.j  a v a2  s .com*/
        Files.write(path, resourceBinary, StandardOpenOption.CREATE_NEW);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return path.getFileName().toString();
}

From source file:com.hortonworks.registries.util.HdfsFileStorageTest.java

@Test
public void testUploadJar() throws Exception {
    Map<String, String> config = new HashMap<>();
    config.put(HdfsFileStorage.CONFIG_FSURL, "file:///");
    fileStorage.init(config);/*from   w  ww.j  ava  2s.  c om*/

    File file = File.createTempFile("test", ".tmp");
    file.deleteOnExit();

    List<String> lines = Arrays.asList("test-line-1", "test-line-2");
    Files.write(file.toPath(), lines, Charset.forName("UTF-8"));
    String jarFileName = "test.jar";

    fileStorage.deleteFile(jarFileName);

    fileStorage.uploadFile(new FileInputStream(file), jarFileName);

    InputStream inputStream = fileStorage.downloadFile(jarFileName);
    List<String> actual = IOUtils.readLines(inputStream);
    Assert.assertEquals(lines, actual);
}

From source file:net.gcolin.simplerepo.test.AbstractRepoTest.java

protected Server createServer(int port, String displayName) throws Exception {
    FileUtils.deleteDirectory(new File("target/repo" + displayName));
    System.setProperty("simplerepo.root", "target/repo" + displayName);
    File repoRoot = new File("target/repo" + displayName);
    repoRoot.mkdirs();//  w w w  .  j  av a  2s  .  c  om
    Files.write(new File(repoRoot, "config.properties").toPath(), Arrays.asList("plugins="),
            StandardCharsets.UTF_8);
    Server server = new Server(port);
    FileUtils.copyDirectory(new File("src/main/webapp"), new File("target/server"));
    WebAppContext app = new WebAppContext("target/server", "/simple-repo");
    app.setAttribute("contextName", displayName);
    app.setExtractWAR(true);
    app.getSecurityHandler()
            .setLoginService(new HashLoginService("Test realm", "src/test/resources/realm.properties"));
    app.setDisplayName(displayName);
    server.setHandler(app);
    server.start();
    return server;
}

From source file:fi.johannes.kata.ocr.utils.files.ExistingFileConnection.java

public void appendLines(List<String> lines) throws IOException {
    Files.write(p, lines, StandardOpenOption.APPEND);
}

From source file:fi.johannes.kata.ocr.utils.files.ExistingFileConnection.java

public void writeNew(List<String> lines) throws IOException {
    Files.delete(p);
    Files.write(p, lines, StandardOpenOption.CREATE);
}

From source file:org.apache.streams.util.schema.FileUtil.java

/**
 * writeFile.//w  ww .  j a  va2s .co  m
 * @param resourceFile resourceFile
 * @param resourceContent resourceContent
 */
public static void writeFile(String resourceFile, String resourceContent) {
    try {
        File path = new File(resourceFile);
        File dir = path.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Files.write(Paths.get(resourceFile), resourceContent.getBytes(), StandardOpenOption.CREATE_NEW);
    } catch (Exception ex) {
        LOGGER.error("Write Exception: {}", ex);
    }
}

From source file:fr.treeptik.cloudunit.config.Http401EntryPoint.java

public void generateLogTraceForFail2ban() {
    log.debug("generateLogTraceForFail2ban");
    String filePath = "/var/log/culogin.log";
    try {/*w w  w .j  a  va  2 s.  c  om*/
        Files.write(Paths.get(filePath), "Access Denied".getBytes(), StandardOpenOption.APPEND);
        Files.write(Paths.get(filePath), System.getProperty("line.separator").getBytes(),
                StandardOpenOption.APPEND);
    } catch (IOException e) {
        log.error("Cannot write to " + filePath + "", e.getMessage());
    }
}