freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Streams and Files

       A file represents organized collection of data. The main advantage of a file is to store data permanently. Once data is stored on Hard Disk, or CD or any other secondary storage media, it is stored permanently. Files are useful to store data on secondary storage media.
      Once a file is created the data of the file can be shared by various programs to display various reports. 

Streams are two types:-

1. Byte oriented streams.(supports byte formatted data to transfer)
2. Character oriented stream.(supports character formatted data to transfer)

Byte oriented streams:-

Java.io.FileInputStream
    To read the data from the destination file to the java application we have to use FileInputSream class.
To read the data from the .txt file we have to read() method.

Java Images

Java.io.FileOutputStream:-

To write the data to the destination file we have to use the FileOutputStream.
To write the data to the destination file we have to use write() method.

Java Images

Java FileOutputStream program

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\text.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}  

intput and output

output:success

FileOutputStream in write string

import java.io.FileOutputStream;
public class Test{
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\text.txt");
String s="Welcome to freetimestudy.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
}catch(Exception e){System.out.println(e);}
}
}  

intput and output

output:now creating file is text.txt and write in Welcome to freetimestudy