Q:

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

belongs to collection: Java File Handling Programs

0

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
  •  

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to read text from file from a specifi... >>
<< Java program to append text/string in a file...