w3resource logo


Introduction to Java Programming

Java: Writing File

Secondary Nav

Introduction

In an earlier tutorial, we have discussed how to read the file using streams. Streams can be of two types Character Stream or byte Stream. Now let’s discuss how to write/create the file using Java program.

Writing File Using FileOutputStream

FileOutputStream creates an OutputStream that you can use to write bytes to a file. Let’s understand popular way to associate a File object with the Output stream:

  • You can pass the filename to the constructor of the FileOutputStream class.
  • You can create a File object by passing the filename to the File constructor. Then, you can pass the File object to the constructor of the FileOutputStream class.

In our program, we will take input from the user using a keyboard and write it to the file. After the prompt “Type characters to write in File – Press Ctrl+z to end ”, a try block holds the while statement. The while statement continues to read until Ctrl+z pressed by the user. In the case of keyboard input, –1 is returned when you press Ctrl+z.

Java Code: 

package filepackage;
import java.io.*;
public class FileWritingStreamWay {
	public static void main(String[] args) {
		InputStream istream;
		OutputStream ostream=null;
		int c;
		final int EOF = -1;
		istream = System.in;
		File outFile =  new File("Data.txt");		 
		System.out.println("Type characters to write in File – Press Ctrl+z to end ");
		try {
			ostream = new FileOutputStream(outFile);
			while ((c = istream.read()) != EOF)
				ostream.write(c);
		} catch (IOException e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				istream.close();
				ostream.close();
			} catch (IOException e) {
				System.out.println("File did not close");
			}
		}
	}
}

Output:

directory structure image

Writing File Using Character Stream (FileWriter)

While the byte stream classes provide sufficient functionality to handle any type of I/O operation, they cannot work directly with Unicode characters. Since one of the main purposes of Java is to support the “write once, run anywhere” philosophy, it was necessary to include direct I/O support for characters. Creation of a FileWriter is not dependent on the file already existing. FileWriter will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an IOException will be thrown.

Java Code: 

package filepackage;
import java.io.*;
public class FileWritingCharacterStream {
	public static void main(String[] args) throws IOException{
		InputStream istream;		
		int c;
		final int EOF = -1;
		istream = System.in;
		FileWriter outFile =  new FileWriter("Data.txt");	
		BufferedWriter bWriter = new BufferedWriter(outFile);
		System.out.println("Type characters to write in File – Press Ctrl+z to end ");
		
		while ((c = istream.read()) != EOF)
			bWriter.write(c);	
		bWriter.close();
	}
}

Java 7 provides new way to handle exception with in try statement. Let’s write same program with Java 7 syntax. To verify output check Data.txt from project root directory.

Java Code: 

package filepackage;
import java.io.*;
public class FileWritingJava7Way {
	public static void main(String[] args) {
		String s = " This line will be written in File";
		System.out.println("Writing to File Data.txt: " + s);
		try (FileWriter outFile = new FileWriter("Data.txt");
				BufferedWriter bWriter = new BufferedWriter(outFile)) {
			bWriter.write(s);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output:

directory structure image

Summary

  • File writing is step by step process which starts with creating file object (open the file), passing the file object to the output stream, writing data to stream, and flush the data to file system and closing all resources.
  • We have discussed various ways to write the file as well as handle the exception.

Java Code Editor:







Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables