Home  >  Core Java

Java FileInputStream and FileOutputStream Example

By Arvind Rai, July 17, 2014
java.io.FileInputStream and java.io.FileOutputStream has been introduced in JDK 1.0. These APIs are used to read and write stream input and output. We can read and write images using these API. In this page we will learn both API separately.

FileInputStream

java.io.FileInputStream reads byte stream from a file system. It has three constructors as below.
FileInputStream(File file) : Accepts File object
FileInputStream(FileDescriptor fdObj) : Accepts FileDescriptor object
FileInputStream(String name): Accepts file path as string.

Find the sample example below.
FileInputStreamDemo.java
package com.cp.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamDemo {
	public static void main(String[] args) throws IOException {
		File file = new File("D:/test.txt");
		FileInputStream fis = new FileInputStream(file);
		//Read file using read()
		int i=0;
	        while((i=fis.read())!=-1){
	    	  System.out.print((char)i);
	        }
                System.out.println();
                fis.close();
                //Read file using read(byte[] b)
                fis = new FileInputStream(file);
                byte[] b = new byte[256];
                while((i=fis.read(b))!=-1){
	    	  System.out.print(new String(b));
	        }
                fis.close();
	}
} 

FileOutputStream

java.io.FileOutputStream writes byte stream into a file system. It has constructors as below.
FileOutputStream(File file) : Accepts File object
FileOutputStream(File file, boolean append) : Accepts File object and a Boolean variable to append.
FileOutputStream(FileDescriptor fdObj) : Accepts FileDescriptor object.
FileOutputStream(String name) : Accepts file path as string.
FileOutputStream(String name, boolean append) : Accepts file path as string and a Boolean variable to append.

Find the sample example of FileOutputStream.
FileOutputStreamDemo.java
package com.cp.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamDemo {
   public static void main(String[] args) throws IOException {
	    File file = new File("D:/test.txt");
	    FileOutputStream fos = new FileOutputStream(file);
	    //write file using write(byte[] b) 
	    fos.write("Hello World! ".getBytes());
	    //write file using write(byte[] b, int off, int len)
	    fos.write("Hello World!".getBytes(),6,6);
	    //write file using write(int b)
	    byte[] b = " Hello World!".getBytes();
	    for(int i=0;i<b.length;i++){
	    	fos.write(b[i]);
	    }
	    fos.close();
	    System.out.println("Done");
   }
} 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us