Write a java program to determine number of bytes written to file using DataOutputStream


This code is an example of how to find the total number of bytes written to a file using the DataOutputStream class in Java.

First, the code creates a new instance of FileOutputStream class and passes the file name file.txt to its constructor. This opens a file for writing. Then, a new instance of DataOutputStream class is created and passed the FileOutputStream object. The DataOutputStream object is used to write a string "This is Java Programs" to the file using the writeBytes() method.

After writing the data, the size() method of DataOutputStream class is called to get the total number of bytes written to the file. The result is stored in bytesWritten variable, and it is printed to the console.

Finally, the DataOutputStream object is closed using the close() method. If an exception occurs during the process, it will be caught and an error message will be printed to the console.

Source Code

import java.io.*;
public class Written_DataSize
{
	public static void main(String[] args)
	{
		try
		{
			FileOutputStream file_output = new FileOutputStream("file.txt");
			DataOutputStream data_output = new DataOutputStream(file_output);
 
			data_output.writeBytes("This is Java Programs");
 
			int bytesWritten = data_output.size();
			System.out.println("Total " + bytesWritten + " bytes are written to Stream");
 
			data_output.close();
		}
		catch (Exception e)
		{
			System.out.println("Exception : " + e.toString());
		}
	}
}

Output

Total 21 bytes are written to Stream