Stream and File Concept In Java
Posted By : Vakeel Malik | 24-Nov-2018
Stream facilitate transporting data from one place to another place. Different streams are needed to send or receive data through different sources, such as to receive data from the keyboard, we need s stream and to send data to a file, we need another.without streams, it is not possible to move data in java.
Stream:-
A Stream carries data just as a water pipe carries water from one place to another place. There are two categories of streams namely 'input stream' and 'output stream '. input streams are the stream which receives or read data while output streams are the stream which sends data or write the data . all streams represented by classes java.io package.
Now let us see how stream works. we know an input stream reads. so to read data from keyboard we can attach the keyboard to an input stream. so that the stream can read the typed on the keyboard.
DataInputStream dis=new DataInputStream(System.in);
In the above statement, we are attaching a keyboard to DataInputStream object. the keyboard is represented by System.in. Now DatatStream objects can read data coming from the keyboard. here System is a class and 'in' is a field of System class. In fact, there are three fields of system class.
1. System.in represents InputStream object. this object represents standard input device by default Keyboard.
2. System.out represents the PrintStream object. this object represents standard output device by default, that is the monitor.
3. System.err represents the PrintStream object. this object represents by default standard output device that is monitor.
so we can also use System.err to print something on the monitor just like System.out
please observe the above keyboards is represented by System.in which internally creates an object of InputStream class. it means is an InputStream.
this is an example how to create and write file in java.
import java.io.*; class CreateFile{ public static void main(String arg[]) throws IOException { //use to read data from keybord DataInputStream dis=new DataInputStream(System.in); // for create file FileOutputStream fileStream =new FileOutputStream("myFile.txt"); System.out.println("Enter test (@ at the end)"); char ch; //writing data into file from keyboard while((ch=(char)dis.read())!='@'){ fileStream.write(ch); } fileStream.close(); } }
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vakeel Malik
Vakeel is a bright Java Developer working in Oodles.