Home Java Writing Files in Java (with examples)

Writing Files in Java (with examples)

The createNewFile() function in Java can create a file. This method produces a boolean value: true if the file was completed successfully, false if it already exists. As you can see, the procedure is encased in a try…catch block. It is required because an IOException is thrown if an error occurs. For example, if the file cannot be created for any reason.

import java.io.File;
import java.io.IOException;

public class CreateFile {  
  public static void main(String[] args) {  
    try {  
      File newObj = new File("codeunderscored.txt");  
      if (newObj .createNewFile()) {  
        System.out.println("File created: " + newObj.getName());  
      } else {  
        System.out.println("File already exists.");  
      }  
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();  
    }  
  }  
}

To create a file in a particular directory (which requires permission), specify the file’s path and escape the “\” character with double backslashes (for Windows). On Mac and Linux, type the route, such as /Users/name/codeunderscored .txt.

import java.io.File;
import java.io.IOException;
  
public class CreateFileDir {  
  public static void main(String[] args) {  
    try {  
      File newObj = new File("Users/Code\\codeunderscored.txt");  
      if (newObj .createNewFile()) {  
        System.out.println(" Created file: " + newObj.getName());  
        System.out.println("Absolute path: " + newObj.getAbsolutePath());  
      } else {  
        System.out.println("File is already there.");  
      }  
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();  
    }  
  }  
}

How to Write to a file

The FileWriter class and its write() method are used in the following example to write some text to the file we created earlier. It’s important to remember that once you’ve finished writing to the file, you should shut it with the close() method:

import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile {  
  public static void main(String[] args) {  
    try {  
      FileWriter newWriter = new FileWriter("codeunderscored .txt");
      newWriter.write("Writing to files in Java is easy peasy!");
      newWriter.close();
      System.out.println("Completed writing to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }  
}

Using BufferedWriter Class

BufferedWriter is a class that allows you to write buffered text. It’s used to create a character-output stream from the text. Characters, strings, and arrays can all be written with it. It has a default buffer size; however, it can be changed to huge buffer size. If no prompt output is required, it is preferable to encapsulate this class with any writer class for writing data to a file.

// Program for writing into a File using BufferedWriter Class

// Importing java input output libraries

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

// Main class
public class BufferedWriterClass {


	public static void main(String[] args)
	{

		// Assigning the file content as input to illustrate
		String text = "Welcome to Codeunderscored ";

		// Try block to check for exceptions
		try {

			// Create a BufferedWriter object
			BufferedWriter bfWriter
				= new BufferedWriter(new FileWriter(
					"/Users/Code/Desktop/underscored.docx"));

			// Writing text to the file
			bfWriter.write(text);

			// Printing file contents
			System.out.print(text);

			// Display message showcasing program execution success
			System.out.print(
				"content added to file successfully");

			// Closing the BufferedWriter object
			bfWriter.close();
		}

		// Catch block for handling exceptions that occur
		catch (IOException e) {

			// Printing the exception message on the console
			System.out.print(e.getMessage());
		}
	}
}

Using the FileOutputStream class

The BufferedWriter class is used to write to a file in this example. However, because this class has a big buffer size, it can write massive amounts of data into the file. It also necessitates the creation of a BufferedWriter object, such as FileWriter, to write content into the file.

It’s used to save unprocessed stream data to a file. Only text can be written to a file using the FileWriter and BufferedWriter classes, but binary data can be written using the FileOutputStream class.

The following example shows how to use the FileOutputStream class to write data to a file. It also necessitates the creation of a class object with the filename to write data to a file. The content of the string is transformed into a byte array, which is then written to the file using the write() method.

// Program for Writing to a File using the FileOutputStream Class


import java.io.FileOutputStream;
import java.io.IOException;

public class WriteUsingFileOutputStream {


	public static void main(String[] args)
	{

		// Assigning the file contents

		String fileContent = "Codeunderscored extravaganza ";
		FileOutputStream outputStream = null;

		// Try block to check if exception occurs
		try {

			// Creating an object of the FileOutputStream
			outputStream = new FileOutputStream("underscored.txt");

			// Storing byte contents from the string
			byte[] strToBytes = fileContent.getBytes();

			// Writing directly into the given file
			outputStream.write(strToBytes);

			// Printing the success message  is optional
			System.out.print(
				"Content added to File successfully.");
		}

		// Catch block handling the exceptions
		catch (IOException e) {

			// Showing the exception/s
			System.out.print(e.getMessage());
		}

		// use of the finally keyword with the try-catch block – to execute irregardless of the 		// exception

		finally {

			// object closure
			if (outputStream != null) {

				//  Second try catch block enforces file closure
				// even if an error happens
	
				try {

					// file connections closure
					// when no exception has happen
					outputStream.close();
				}

				catch (IOException e) {

					// shows exceptions that are encountered
					System.out.print(e.getMessage());
				}
			}
		}
	}
}

The writeString() function

Version 11 of Java supports this approach. Four parameters can be passed to this method. The file location, character sequence, charset, and options are all of these. The first two parameters are required for this method to write to a file. It saves the characters as the file’s content. It returns the path to the file and can throw four different types of exceptions. When the file’s content is short, it’s best to use it.

It demonstrates how to put data into a file using the writeString() function from the Files class. Another class, Path, is used to associate the filename with the destination path for the content.

The readString() function of the Files class reads the content of any existing file. The code then uses the latter to ensure that the text is appropriately written in the file.

// Program for Writing Into a File using the writeString() Method

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

// Main class
public class WriteStringClass {

	public static void main(String[] args)
		throws IOException
	{
		//file content assigning
		String text
			= "Codeunderscored extravaganza!";

		// definition of the file' name
		Path fileName = Path.of(
			"/Users/Code/Desktop/undercored.docx");

		// Writing into the file
		Files.writeString(fileName, text);

		// Read file contents
		String fileContent = Files.readString(fileName);

		// Printing the files' content
		System.out.println(fileContent);
	}
}

Conclusion

The Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class since it is utilized in java file handling. There are numerous ways to write to a file in Java, as there are numerous classes and methods that can accomplish this. They include the writeString() function, FileWriterclass, BufferedWriter class and the FileOutputStream.

You may also like

Leave a Comment