Java file DataOutputStream


 

Java file DataOutputStream

This section demonstrates you the use of DataOutputStream class.

This section demonstrates you the use of DataOutputStream class.

Java file DataOutputStream

This section demonstrates you the use of DataOutputStream class.

The class DataOutputStream allow a programmer to write primitive Java data types to an output stream in a portable way. This class provide different method to write different type of data like writeInt() for integer, writeChars() for string etc.

In the given example, we have created an instance of FileOutputStream with newfile.txt as the file name to be created. Then we have passed the input stream object in the constructor of the DataOutputStream. Then using the methods of DataOutputStream, we have write the data into the file.

Here is the code:

import java.io.*;

public class FileDataOutputStream {
	public static void main(String[] args) throws Exception {
		try {
			FileOutputStream fos = new FileOutputStream("cities.dat");
			DataOutputStream dos = new DataOutputStream(fos);
			dos.writeUTF("RoseIndia Private Technologies");
			dos.writeUTF("Rohini, Delhi");
			dos.writeInt(1111111111);

			dos.flush();
			dos.close();
		} catch (Exception e) {
		}
	}
}

Through the above code, you can write any type of data into the file.

Ads