What's the simplest way to create and write to a (text) file in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Using Google's Guava library, we can create and write to a file very easily.
The example creates a new
fruits.txt
file in the project root directory.If you already have the content you want to write to the file (and not generated on the fly), the
java.nio.file.Files
addition in Java 7 as part of native I/O provides the simplest and most efficient way to achieve your goals.Basically creating and writing to a file is one line only, moreover one simple method call!
The following example creates and writes to 6 different files to showcase how it can be used:
I think this is the shortest way:
Here we are entering a string into a text file:
We can easily create a new file and add content into it.
The simplest way I can find:
It will probably only work for 1.7+.