File Handling
File Handling
File Handling
Java I/O is used to process the input and produce the output.
Java program perform input and output through stream.
A stream is linked to a physical device by the java I/O system to make input and output
operation in java.
In general, Stream means continuous flow of data, a sequence of data.
To bring in information, a program opens an input stream on an source and reads the
information sequentially, as shown here:
1. Byte Stream :
Page 1 of 9
It is used when reading or writing binary data.
2. Character Stream :
Page 2 of 9
PrintStream Output Stream that contain print() and println() method
These classes define several key methods. Two most important are
Page 3 of 9
FileWriter Output stream that writes to file.
These classes define several key methods. Two most important are
Que:
1. Explain how to create a text file in context to file handling.
2. Write Java syntax to create a new text file.
3. Write syntax of writing a text file in Java.
4. Write syntax of reading text file in Java.
Ans:
Creating a File
Page 4 of 9
To create a file use the following syntax:
Ex:
File f = new File ("C:/java/hello.txt");
Reading a File
1
void close() throws IOException
- Throws an IOException.
2
int read() throws IOException
-Returns the next byte of data and -1 will be returned if it's the end of the file.
import java.io.*;
Page 5 of 9
class SimpleRead
try
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fin.close();
catch(Exception e)
system.out.println(e);
Writing a File
1
void close() throws IOException
-Throws an IOException.
2
void write(int w)throws IOException
import java.io.*;
class Test
try
byte b[]=s.getBytes();
fout.write(b);
fout.close();
Page 7 of 9
System.out.println("success...");
catch(Exception e)
system.out.println(e);
Output:success...
Example of Reading the data of current java file and writing it into another file
import java.io.*;
class C
int i=0;
while((i=fin.read())!=-1)
fout.write((byte)i);
fin.close();
System.out.println(“copying done!”);
Page 8 of 9
}
Page 9 of 9