Home  >  Core Java

Java DataInputStream and DataOutputStream Example

By Arvind Rai, June 14, 2014
In this page we will learn how to use Java DataInputStream and DataOutputStream. These stream is used to handle primitive data types values. Read and write primitive data in portable way using these API. Find the sample example how to use it.

Java DataInputStream Example

java.io.DataInputStream reads primitive data from a file through an input stream which is machine indepenedednt. DataInputStream is not thread safe.
DataInputStreamDemo.java
package com.cp.io;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class DataInputStreamDemo {
	public static void main(String[] args) throws IOException {
			String file = "D:/cp/file.txt";
			FileInputStream fin = new FileInputStream(file);
			DataInputStream din = new DataInputStream(fin);
			
			byte b[] = new byte[0];
		    din.read(b);
		    
		    String val;
	        while((val = din.readLine()) != null){
	          String u = val.toUpperCase();
	          System.out.println(u);
	        }
	        
	        fin.close();
	        din.close();
	}
} 

Java DataOutputStream Example

java.io.DataOutputStream helps to write primitive data type in a file as an output stream. Data input stream can then read it back.
DataOutputStreamDemo.java
package com.cp.io;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataOutputStreamDemo {
	public static void main(String[] args) throws IOException {
		String strFile = "D:/cp/file.txt";
		FileOutputStream fos = new FileOutputStream(strFile);
		DataOutputStream dos = new DataOutputStream(fos);
		int num = 100;
		dos.writeInt(num);
		dos.flush();
		dos.close();
		System.out.println("Done");
	}
} 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us