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
If you wish to have a relatively pain-free experience you can also have a look at the Apache Commons IO package, more specifically the
FileUtils
class.Never forget to check third-party libraries. Joda-Time for date manipulation, Apache Commons Lang
StringUtils
for common string operations and such can make your code more readable.Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.
To create file without overwriting existing file:
Reading collection with customers and saving to file, with JFilechooser.
Note that each of the code samples below may throw
IOException
. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.Note that each of the code samples below will overwrite the file if it already exists
Creating a text file:
Creating a binary file:
Java 7+ users can use the
Files
class to write to files:Creating a text file:
Creating a binary file:
If you for some reason want to separate the act of creating and writing, the Java equivalent of
touch
iscreateNewFile()
does an existence check and file create atomically. This can be useful if you want to ensure you were the creator of the file before writing to it, for example.