Streams
Streams
Input Streams: Input streams are used to read the data from various input devices
like keyboard, file, network, etc.
Output Streams: Output streams are used to write the data to various output
devices like monitor, file, network, etc.
FileInputStream
------------------
It is predefined class to read data from file.
read() is predefined method to read data.
read() method throws an IOException[Checked exception].
Incase of end of file, read() returns -1.
notepad demo.txt
demo.txt
This is file program
ReadContent.java
import java.io.*;
class ReadContent
{
public static void main(String args[])
{
try
{
FileInputStream f=new FileInputStream("demo.txt");
int d=f.read();
System.out.print((char)d);
d=f.read();
System.out.print((char)d);
d=f.read();
System.out.print((char)d);
f.close();
}
catch(IOException e)
{System.out.println(e);}
}
}
notepad stud.txt
----------------------
Roll Name Branch
1 Ram CSE
2 Gita IT
3 Ramesh CST
4 Suresh MECH
program to read stud.txt file
-----------------------------
import java.io.*;
class ReadStud
{
public static void main(String args[])
{
try
{
FileInputStream f=new FileInputStream("stud.txt");
int d;
while((d=f.read())!=-1)
{
System.out.print((char)d);
}
f.close();
}
catch(IOException e)
{System.out.println(e);}
}
}
System.out.print((char)d);
Thread.sleep(200);
}
f.close();
}
catch(Exception e)
{System.out.println(e);}
}
}
FileOutputStream
-----------------
It is predefined class to create a new file in program directory.
write() is predefined method to write data in to the file.
Constructor is used to create new file.
FileOutputStream f=new FileOutputStream("demo.txt") //create new file
FileOutputStream f=new FileOutputStream("demo.txt",true); //open in append mode
getBytes()
------------
This method is used to convert string to byte array.
It is part of String class.
byte r[]="This is java".getBytes();
import java.io.*;
class PrintB
{
public static void main(String args[])
{
byte r[]="ABCDEF".getBytes();
for(byte val:r)
System.out.print(val+" ");
}
}