Home » Java programs » Java file handling programs

Java program to determine number of bytes written to file using DataOutputStream



In this java program, we are going to learn how to get (determine) the number of bytes written to a file using DataOutputStream? Here, we will write text in file and print the number of written bytes.
Submitted by IncludeHelp, on October 19, 2017

Given a file and we have to write text and print the total number of written bytes using DataOutputSteam using Java program.

There is a file named "IncludeHelp.txt" which is stored at my system in "E:" drive under "JAVA" folder (you can choose your path), and in this file we will write some text and print the total number of written bytes.

Example:

Text to write in file:  "IncludeHelp is for computer science students."
Output: Total 45 bytes are written to stream.

First of all we will create an object of FileOutputStream by passing the file’s path and then we will create an object of DataOutputStream by passing object of FileOutputStream.

Then, we will write the text into file using writeBytes() method of DataOutputStream and finally we will get the size of the file by using size() method of DataOutputStream class.

In this program,

  • objFOS is the object of FileOutputStream class
  • objDOS is the object of DataOutputStream class


Consider the program

import java.io.*;

public class ExToDetermineWrittenDataSize
{
	//Java program to determine number of bytes written to file using DataOutputStream
	public static void main(String[] args){
		try
		{
		    FileOutputStream objFOS = new FileOutputStream("E:/includehelp.txt");
		    DataOutputStream objDOS = new DataOutputStream(objFOS);

		    objDOS.writeBytes("IncludeHelp is for computer science students.");
		    int bytesWritten = objDOS.size();
		    System.out.println("Total " + bytesWritten + " bytes are written to stream.");
		    objDOS.close();			
		}
		catch(Exception ex)
		{
			System.out.println("Exception: " + ex.toString());
		}

	  }
}

Output

Total 45 bytes are written to stream.





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.