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
Here's a little example program to create or overwrite a file. It's the long version so it can be understood more easily.
Here are some of the possible ways to create and write a file in Java :
Using FileOutputStream
Using FileWriter
Using PrintWriter
Using OutputStreamWriter
For further check this tutorial about How to read and write files in Java .
If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.
There are few points to note:
StandardCharsets
.try-with-resource
statement in which resources are automatically closed after the try.Though OP has not asked but just in case we want to search for lines having some specific keyword e.g.
confidential
we can make use of stream APIs in Java:Use:
Creating a sample file:
A very simple way to create and write to a file in Java:
Reference: File create Example in java