Home »
Java Programs
Java program to write Bytes using ByteStream
In this program, we are going to learn to write bytes using ByteStream? To write data 'byte-by-byte' in the file, we will use writeBytes() method.
Here, we are using two classes 1) FileOutputStream and 2) DataOutputStream,
FileOutputStream class is using to create an object by passing file name and DataOutputStream class is using to create an object to invoke writeBytes() method to write data in the file.
Consider the program:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExByteStreamFile
{
public static void main(String[] args)
{
try
{
// Here FO is the object of the file which is created to write.
FileOutputStream FO=new FileOutputStream("E:/TH.txt");
// Here F is the object of the file from which we have to write the content.
DataOutputStream F=new DataOutputStream(FO);
// These are the Input which is to be write on the file TH.txt
F.writeBytes("Gwalior");
F.writeBytes("\n");
F.writeBytes("Indore");
F.writeBytes("\n");
F.writeBytes("Bhopal");
F.writeBytes("\n");
F.writeBytes("7008");
F.writeBytes("\n");
// FO colsed
FO.close();
// F closed
F.close();
//reading data
FileInputStream FI=new FileInputStream("E:/TH.txt”);
DataInputStream DI=new DataInputStream(FI);
String s="";
// This loop will print the whole whole inputted data on the screen
while((s=DI.readLine())!=null)
{
System.out.println(s);
}
}
// If an error occurrs during the process
catch(IOException e)
{
System.out.println(e);
}
}
}
Output
Gwalior
Indore
Bhopal
7008