Languages
[Edit]
EN

Java - create and write file

0 points
Created by:
Kourtney-White
635

In this article, we would like to show you how to create and write files in Java.

There are several methods to create and write files in Java:

  • Files.newBufferedWriter (Java 8)
  • Files.write (Java 7)
  • FileOutputStream (Java 7)
  • File.createNewFile
  • PrintWriter

1. Files.newBufferedWriter

Edit

In this example, we use Files.newBufferedWriter() method to create a new example.txt file and write some text inside it. If the file already exists, the content will be overwritten.

Result:

Java - Files.newBufferedWriter method result
Java - Files.newBufferedWriter method result

2. Files.write

Edit

In this example, we use Files.write() method to create a new example.txt file and write some text inside it. If the file already exists, the content will be overwritten.

Result:

Java - Files.write() method result
Java - Files.write() method result

3. FileOutputStream

Edit

In this example, we use FileOutputStream to create a new example.txt file and write some text inside it. If the file already exists, the content will be overwritten.

4. File.createNewFile

Edit

The File.createNewFile() method returns:

  • true - if the file doesn't exist and was created successfully,
  • false - if the file is already exists

In this example, we use File.createNewFile method to create a new example.txt file and  FileWriter to write some text inside it. If the file exists, the FileWriter will overwrite the content.

Output:

Result:

Java - File.createNewFile() with FileWriter result
Java - File.createNewFile() with FileWriter result

5. PrintWriter

Edit

In this example, we use PrintWriter class to create a new example.txt file and write some text inside it. If the file already exists, the content will be overwritten.

Result:

Java - create and write file using PrintWriter - result
Java - create and write file using PrintWriter - result
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java IO Tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join