Adam Bien's Weblog

Tuesday Mar 04, 2014

Java 7+: Writing A String To File--A One Liner


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class StringToFile {
    public static void main(String[] args) throws IOException {
        String msg = "hello";
        Files.write(Paths.get("./duke.txt"), msg.getBytes());
    }
}


There are probably programming languages out there which achieve the same with fewer characters. In Java, however, we have IDEs :-).

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!


Special Event: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014

A book about rethinking Java EE Patterns

Comments:

Very cool indeed! There's also a read capability, which I added to the write:

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class StringToFile {

public static void main(String[] args) throws IOException {
write();
read();
}

public static void write() throws IOException {
String msg = "hello you\nthis is just a test\n";
Files.write(Paths.get("./duke.txt"), msg.getBytes());
}

public static void read() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("./duke.txt"), Charset.defaultCharset());
for (String line : lines) {
System.out.println("line read: " + line);
}
}
}

Posted by Pierre Clement on March 04, 2014 at 04:45 PM CET #

viewer or fewer characters?

Posted by Leoš Literák on March 04, 2014 at 05:00 PM CET #

@Leos,

fewer of course. Thanks for catching that!

Posted by Adam Bien on March 04, 2014 at 06:38 PM CET #

@Pierre,

nice! but: http://www.adam-bien.com/roller/abien/entry/reading_a_file_into_a

:-)

thanks for writing code into a comment field! :-),

cheers,

adam

Posted by Adam Bien on March 04, 2014 at 06:39 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
...the last 150 posts
...the last 10 comments
Links
License