Home  >  Core Java

Java FileDescriptor Example with FileInputStream and FileOutputStream

By Arvind Rai, July 16, 2014
java.io.FileDescriptor has been introduced in JDK 1.0. FileDescriptor represents an open file, socket. FileDescriptor is used with FileInputStream and FileOutputStream. Two instances of FileOutputStream or FileInputStream can communicate using FileDescriptor. In this page I will show two example which will use FileDescriptor, one with FileOutputStream and second with FileInputStream.
FileDescriptorDemoOne.java
package com.cp.io;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileDescriptorDemoOne {
	public static void main(String[] args) throws IOException {
            File file = new File("D:/test.txt");
	    FileOutputStream fos1 = new FileOutputStream(file);
	    FileDescriptor fd = fos1.getFD(); 
	    //passing FileDescriptor to another  FileOutputStream
	    FileOutputStream fos2 = new FileOutputStream(fd);
	    fos2.write("Hello World!".getBytes());
	    fos1.close();
	    fos2.close();
	}
} 
The above example shows the practical use of FileDescriptor. FileOutp utStream can contain FileDescriptor. In the example we have created an instance of FileOutputStream and then got FileDescriptor. Pass the the FileDescriptor instance to another FileOutputStream instance. What we get is that the second FileOutputStream instance gets the context of first FileOutputStream.

Now find the example of FileDescriptor with FileInputStream.
FileDescriptorDemoTwo.java
package com.cp.io;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
public class FileDescriptorDemoTwo {
	public static void main(String[] a) throws IOException {
	    File file = new File("D:/test.txt");
	    FileInputStream fis1 = new FileInputStream(file);
	    FileDescriptor fd = fis1.getFD();
	    //passing FileDescriptor to another  FileInputStream
	    FileInputStream fis2 = new FileInputStream(fd);
	    int i=0;
	    while((i=fis2.read())!=-1){
	    	System.out.print((char)i);
	    }
	    fis1.close();
	    fis2.close();
   }
} 
Output will be Hello World!
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us