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.

Java File Handling Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.