codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
☕

Java Programming

44 / 65 topics
43Java Files44Java Create & Write Files45Java Read Files46Java Delete Files47Java I/O Streams48FileInputStream & FileOutputStream49BufferedReader & BufferedWriter
Tutorials/Java Programming/Java Create & Write Files
☕Java Programming

Java Create & Write Files

Updated 2026-05-12
30 min read

Java Create & Write Files

In this tutorial, you'll learn how to create and write files in Java using the FileWriter class. File handling is a fundamental aspect of programming, allowing your applications to store data persistently on disk. Understanding how to create and write files is crucial for building robust applications that can manage data effectively.

Introduction

In Java, file handling involves reading from and writing to files. The FileWriter class is part of the Java I/O (Input/Output) package and provides a convenient way to write character data to files. This tutorial will guide you through the process of creating new files and writing text to them using FileWriter.

Creating New Files

To create a new file in Java, you can use the File class along with the FileWriter class. The File class represents a file or directory pathnames, while the FileWriter class is used for writing character files.

Example 1: Creating and Writing to a File

Let's start by creating a simple Java program that creates a new file and writes some text to it.

CreateAndWriteToFile.java
1import java.io.FileWriter;
2import java.io.IOException;
3
4public class CreateAndWriteToFile {
5 public static void main(String[] args) {
6 // Specify the file path
7 String filePath = "example.txt";
8
9 try (FileWriter writer = new FileWriter(filePath)) {
10 // Write some text to the file
11 writer.write("Hello, Java!");
12 System.out.println("File created and written successfully.");
13 }; catch (IOException e) {
14 System.err.println("An error occurred while writing to the file: " + e.getMessage());
15 }
16 }
17}
Output
File created and written successfully.

Explanation

  1. Import Statements: We import FileWriter and IOException from the java.io package.
  2. File Path: We specify the file path where we want to create the new file.
  3. Try-With-Resources: We use a try-with-resources statement to ensure that the FileWriter is closed automatically after the block of code is executed. This helps in managing resources efficiently and prevents resource leaks.
  4. Writing Text: Inside the try block, we write "Hello, Java!" to the file using the write() method of FileWriter.
  5. Exception Handling: We catch any IOException that might occur during file operations and print an error message.

Writing Multiple Lines

You can also write multiple lines to a file by using the newLine() method of FileWriter.

Example 2: Writing Multiple Lines to a File

Let's modify the previous example to write multiple lines to the file.

WriteMultipleLines.java
1import java.io.FileWriter;
2import java.io.IOException;
3
4public class WriteMultipleLines {
5 public static void main(String[] args) {
6 String filePath = "multiple_lines.txt";
7
8 try (FileWriter writer = new FileWriter(filePath)) {
9 writer.write("Line 1");
10 writer.newLine();
11 writer.write("Line 2");
12 writer.newLine();
13 writer.write("Line 3");
14
15 System.out.println("Multiple lines written successfully.");
16 } catch (IOException e) {
17 System.err.println("An error occurred while writing to the file: " + e.getMessage());
18 }
19 }
20}
Output
Multiple lines written successfully.

Explanation

  1. Writing Lines: We use writer.newLine() to insert a newline character after each line of text.
  2. Result: The file will contain three lines: "Line 1", "Line 2", and "Line 3".

Overwriting Files

If the specified file already exists, using FileWriter will overwrite its contents. If you want to append to an existing file instead, you can use the FileWriter constructor that takes a boolean parameter.

Example 3: Appending to an Existing File

Let's see how to append text to an existing file.

AppendToFile.java
1import java.io.FileWriter;
2import java.io.IOException;
3
4public class AppendToFile {
5 public static void main(String[] args) {
6 String filePath = "example.txt";
7
8 try (FileWriter writer = new FileWriter(filePath, true)) { // Second parameter is true for appending
9 writer.write(" This text will be appended.");
10 System.out.println("Text appended successfully.");
11 } catch (IOException e) {
12 System.err.println("An error occurred while writing to the file: " + e.getMessage());
13 }
14 }
15}
Output
Text appended successfully.

Explanation

  1. Appending Mode: The second parameter of the FileWriter constructor is set to true, which enables appending mode. This means that any text written to the file will be added at the end, rather than overwriting existing content.

Best Practices

  • Use Try-With-Resources: Always use try-with-resources to ensure that resources like FileWriter are closed properly.
  • Handle Exceptions: Properly handle IOException to manage errors related to file operations.
  • Check File Existence: Before writing, you might want to check if the file exists and decide whether to create it or append to it.

Practical Example

Let's put everything together in a practical example. We'll create a program that writes user input to a file.

Example 4: Writing User Input to a File

WriteUserInput.java
1import java.io.FileWriter;
2import java.io.IOException;
3import java.util.Scanner;
4
5public class WriteUserInput {
6 public static void main(String[] args) {
7 String filePath = "user_input.txt";
8 Scanner scanner = new Scanner(System.in);
9
10 System.out.println("Enter text to write to the file (type 'exit' to quit):");
11
12 try (FileWriter writer = new FileWriter(filePath)) {
13 while (true) {
14 String input = scanner.nextLine();
15 if (input.equalsIgnoreCase("exit")) {
16 break;
17 }
18 writer.write(input);
19 writer.newLine();
20 }
21 System.out.println("Text written successfully.");
22 } catch (IOException e) {
23 System.err.println("An error occurred while writing to the file: " + e.getMessage());
24 } finally {
25 scanner.close();
26 }
27 }
28}

Explanation

  1. User Input: We use a Scanner object to read user input from the console.
  2. Loop for Input: The program runs in a loop, continuously reading input until the user types "exit".
  3. Writing Input: Each line of input is written to the file followed by a newline character.
  4. Closing Scanner: We close the Scanner object in the finally block to ensure it's closed even if an exception occurs.

Summary

  • FileWriter: Used for writing character data to files.
  • Try-With-Resources: Ensures that resources are closed automatically.
  • Appending Mode: Use the second parameter of FileWriter constructor as true to append text to existing files.
  • Best Practices: Handle exceptions, use try-with-resources, and check file existence.

What's Next?

Now that you know how to create and write files in Java, the next step is learning how to read from files. In the upcoming tutorial on "Java Read Files," we'll explore how to read text from files using FileReader and other related classes. Stay tuned!


PreviousJava FilesNext Java Read Files

Recommended Gear

Java FilesJava Read Files