=============Java I/O Tutorial===================================
File Handling:--
the file handling define how we can read and write data on the file .
java.IO package contain all the classes through which we can perform all the
input/output operation in the file.
===========================================
File Handling methods:-------------
1) canRead() ::-- it is used to check can read or not from the file ,return type boolean
2)canWrite() ::- it is used to check can write or not in the file ,return type boolean
3)createNewFile() ::-- it is use to create a new file .
4)delete() ::-- it is used to delete the file
5)exists() ::-- it is used to check file present or not
6) length() ::--it is used to find length of file
7)getName() ::--we can find the name of file
8)getAbsolutePath() ::-- we can find the file location , where is located
9)List() ::--it is tell how many file present in directory
10)Mkdir() ::-It is used to create the directory
11)read() ::--read the data from the file
12)write() ::---write the data on the file
13) renameTo ::- it is use to rename the file
======================================================
File Handling Classes :----
1)File ::- it is a class , it is used to create file .
2)FileReader ::-
3)FileWriter
4)BufferedReader
5)BufferedWriter
6)FileInputStream
7)FileOutputStream
8)BufferedInputStream
9)BufferedOutputStream
10)PrintWriter
11)InputStream
12)OutputStream
===============================================================
Program--
-------------------------------
1)Copy data from one file to another
public class CopyFile {
public static void main(String[] args) throws IOException {
FileInputStream fs = new FileInputStream
("C:\\Users\\LENOVO\\Desktop\\NewIO.txt");
FileOutputStream fo = new FileOutputStream
("C:\\Users\\LENOVO\\Desktop\\New.txt");
int i=0;
while((i=fs.read())!=-1) {
fo.write((char)i);
System.out.println("data copy");
--------------------------------------------------------
2)Write data on the file
public class DemoFileWrite {
public static void main(String[] args) throws IOException {
//File f = new File ();
FileWriter fw = new FileWriter("C:\\Users\\LENOVO\\Desktop\\NewIO2.txt",true);
fw.write(100);
fw.write("\n");
fw.write("durga\nsoftware");
char[] ch = {'a','b','c'};
fw.write(ch);
fw.flush();
fw.close();
--------------------------
3)write on the file using printwriter
public class DemoPrintWriter {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
PrintWriter pw = new PrintWriter("D:\\New folder\\New.txt");
pw.write(100);
pw.println(100);
pw.println(true);
pw.println("durga");
pw.flush();
pw.close();
---------------------------------
4) Read a file character wise
public class FileReaderDemo {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("D:\\New folder\\New.txt");
int i;
while((i=fr.read())!=-1) {
System.out.print((char)i);
fr.close();
catch(IOException e) {
System.out.println("Exception handled");
}}}
o/P
------------------------------------------
5) create a file
public class FileIOPackage {
public static void main(String[] args) throws IOException {
File f = new File ("C:\\Users\\LENOVO\\Desktop\\NewIO3.txt");
if(f.createNewFile()) {
System.out.println("file succesfully created");
else {
System.out.println("file already exists");
} } }
------------------------------------------
Example :--file Merger
public class DemoFileMerger {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter("D:\\Newfolder\\file3.txt");
BufferedReader br = new BufferedReader(new FileReader("D:\\Newfolder \\
file1.txt"));
String line = br.readLine();
while(line!=null) {
pw.println(line);
line=br.readLine();
br = new BufferedReader(new FileReader("D:\\Newfolder\\file2.txt"));
line =br.readLine();
while(line!=null) {
pw.println(line);
line=br.readLine();
pw.flush();
br.close();
pw.close();
==================================================
==========================================================
What is File I/O:----------?
Java I/O stream is the flow of data that you can either read from, or you can write to.
It is used to perform read and write operations in file permanently. Java uses streams to perform these
tasks. Java I/O stream is also called File Handling, or File I/O. It is available in java.io package.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.
----------------------------------------------------------------------------------------------------
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to break a
String. It is a legacy class of Java.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
methods:----
boolean hasMoreTokens() It checks if there is more tokens available.
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
boolean hasMoreElements() It is the same as hasMoreTokens() method.
Object nextElement() It is the same as nextToken() but its return type is Object.
int countTokens() It returns the total number of tokens.
NOTE::-- The StringTokenizer class is deprecated now. It is recommended to use the split() method of
the String class or the Pattern class that belongs to the java.util.regex package.
Example:----1
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
Output:
my
name
is
khan
---------------------------------
example:--2
public class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
// to count the string of countTokens() method of the StringTokenizer class
StringTokenizer st1 = new StringTokenizer("Hello Everyone Have a nice day"," ");
System.out.println("Total number of Tokens: "+st1.countTokens());
Output:
Next token is : my
Total number of Tokens: 6
--------------------------------------------------------------
===============================================================
Serialization::--
Serialization in Java allows us to convert an Object to stream that we can send over the network or save
it as file or store in DB for later usage.
Deserialization is the process of converting Object stream to actual Java Object to be used in our
program.
example::--- of serializable
import java.io.Serializable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Employee implements Serializable {
private int id;
private String name;
public Employee(int id, String name){
this.id = id;
this.name= name;
public class SerializationDemo {
// serialize the given object and save it to file
public static void main(String[] args)throws IOException
Employee e = new Employee(101 , "Irshad" );
FileOutputStream fos = new FileOutputStream("D:\\New folder\\ABC.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e);
oos.flush();
fos.close();
System.out.println("success");
=========================================================
Stream:----------------------------
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is
like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");
example:-
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral
device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral
device or socket.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes.
Methods:----
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws IOException is used to write an array of byte to the current output
stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of
bytes.
Useful methods of InputStream
MethodDescription
1) public abstract int read()throws IOException reads the next byte of data from the input stream. It
returns -1 at the end of the file.
2) public int available()throws IOException returns an estimate of the number of bytes that can be
read from the current input stream.
3) public void close()throws IOException is used to close the current input stream.