OOPS With Java Unit 2
OOPS With Java Unit 2
Exception Handling
Step 2: Create a byte array of a fixed size to read a chunk of data from the file.
Step 3: Use the read() method of the FileInputStream class to read data from the file into the
byte array. This method returns the number of bytes read , or -1 if the end of the file
has been reached.
Step 4: Continue reading data from the file until the read() method returns -1.
Step 5: Close the FileInputStream object using to release the close() method to release any
system resources associated with it.
Following example demonstrates how to use Fileinputstream
to read data from a file :
import java.io.*
In the example above, we create a
public class ReadFileExample {
FilelnputStream object to read data
public static void main(String[] args) {
from a file called "file.txt".
try {
FileInputStream fileinput = new
We then create a byte array of size 1024
FileInputStream ("file.txt");
to read a chunk of data from the file.
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileInput.read(buffer))!=-1){
System.out.println/new String buffer, 0, bytesread));
} We use the read() method to read data
fileInput.close(); into the buffer untill the end of the file is
} catch (IOException e) { reached, and then we close the
e.printStackTrace(); FilelnputStream object.
}
} Finally, we print the data that we read
} from the file to the console
Writing in a file: 1. In Java, FileOutputStream class in used for writing binary data to a file.
Step 2: Create a byte array that contains the date that you want to write to the file.
Step 3: Use the write() method of the FileOutputStream class to write the data to the File
This method writes the entire array to the the file.
Step 4: Close the FileOutputStream object using the close() method to release any system
resources associated with it.