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.
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.
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.
Let's start by creating a simple Java program that creates a new file and writes some text to it.
1import java.io.FileWriter;2import java.io.IOException;34public class CreateAndWriteToFile {5public static void main(String[] args) {6// Specify the file path7String filePath = "example.txt";89try (FileWriter writer = new FileWriter(filePath)) {10// Write some text to the file11writer.write("Hello, Java!");12System.out.println("File created and written successfully.");13}; catch (IOException e) {14System.err.println("An error occurred while writing to the file: " + e.getMessage());15}16}17}
File created and written successfully.
FileWriter and IOException from the java.io package.FileWriter is closed automatically after the block of code is executed. This helps in managing resources efficiently and prevents resource leaks.write() method of FileWriter.IOException that might occur during file operations and print an error message.You can also write multiple lines to a file by using the newLine() method of FileWriter.
Let's modify the previous example to write multiple lines to the file.
1import java.io.FileWriter;2import java.io.IOException;34public class WriteMultipleLines {5public static void main(String[] args) {6String filePath = "multiple_lines.txt";78try (FileWriter writer = new FileWriter(filePath)) {9writer.write("Line 1");10writer.newLine();11writer.write("Line 2");12writer.newLine();13writer.write("Line 3");1415System.out.println("Multiple lines written successfully.");16} catch (IOException e) {17System.err.println("An error occurred while writing to the file: " + e.getMessage());18}19}20}
Multiple lines written successfully.
writer.newLine() to insert a newline character after each line of text.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.
Let's see how to append text to an existing file.
1import java.io.FileWriter;2import java.io.IOException;34public class AppendToFile {5public static void main(String[] args) {6String filePath = "example.txt";78try (FileWriter writer = new FileWriter(filePath, true)) { // Second parameter is true for appending9writer.write(" This text will be appended.");10System.out.println("Text appended successfully.");11} catch (IOException e) {12System.err.println("An error occurred while writing to the file: " + e.getMessage());13}14}15}
Text appended successfully.
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.FileWriter are closed properly.IOException to manage errors related to file operations.Let's put everything together in a practical example. We'll create a program that writes user input to a file.
1import java.io.FileWriter;2import java.io.IOException;3import java.util.Scanner;45public class WriteUserInput {6public static void main(String[] args) {7String filePath = "user_input.txt";8Scanner scanner = new Scanner(System.in);910System.out.println("Enter text to write to the file (type 'exit' to quit):");1112try (FileWriter writer = new FileWriter(filePath)) {13while (true) {14String input = scanner.nextLine();15if (input.equalsIgnoreCase("exit")) {16break;17}18writer.write(input);19writer.newLine();20}21System.out.println("Text written successfully.");22} catch (IOException e) {23System.err.println("An error occurred while writing to the file: " + e.getMessage());24} finally {25scanner.close();26}27}28}
Scanner object to read user input from the console.Scanner object in the finally block to ensure it's closed even if an exception occurs.FileWriter constructor as true to append text to existing files.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!