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!
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 #
echo hello > ./duke.txt
Who needs an IDE for a task like that. Stupidest blog post ever.
Posted by Duh on March 20, 2016 at 04:37 PM CET #
This is really handy for a quick file output. Short and to the point. Best blog post ever.
Posted by Michael Idengren on June 20, 2016 at 09:06 PM CEST #
Using IDEs to spit out verbose code (i don't this the above is verbose) was called 'code vomit' by a nice scala speaker once ;)
Posted by comrad on September 06, 2016 at 09:46 AM CEST #
Nice catch!
Posted by Dorival Querino da Silva on December 29, 2016 at 06:18 PM CET #
Hi,
You have written very nice article. I acquired good knowledge about Java. I will follow up your blog for future post.
Posted by Java Online Training on April 14, 2017 at 11:53 AM CEST #