File Handling In Java
File Handling
In Java File handling, FileInputStream and FileOutputStream classes are used.
In Java, Byte streams are used to perform input and output of 8-bit bytes. While there are many classes related to byte streams but commonly used classes are FileInputStream and FileOutputStream.
FileOutputStream class
FileOutputStream is an output stream, which is used to write the data to a file.
We can write byte-oriented as well as character-oriented data. If we want to write primitive values, we need to use FileOutputStream.
Let’s see an example, given below.
Code
- import java.io.*;
- public class FileHandlingExample {
- public static void main(String args[]) {
- try {
- FileOutputStream fos = new FileOutputStream("Java.txt");
- String s1 = "Java is a object oriented programing language";
- byte b[] = s1.getBytes(); //convert string into byte array
- fos.write(b);
- fos.close();
- System.out.println("Run successfully.....");
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- }
Output
FileInputStream class
FileInputStream class obtains input bytes from a file. It is used to read streams of raw bytes such as read image, audio, video etc.
Let’s see an example, given below.
Code
- import java.io.*;
- public class FileHandlingExample {
- public static void main(String args[]) {
- try {
- FileInputStream fis = new FileInputStream("Java.txt");
- int i = 0;
- while ((i = fis.read()) != -1) {
- System.out.print((char) i);
- }
- fis.close();
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- }
Output
Now let’s see another example to read the data of current Java file and write it into another file.
Code
- import java.io.*;
- public class FileHandlingExample {
- public static void main(String args[]) throws Exception {
- FileInputStream fis = new FileInputStream("Simple.java");
- FileOutputStream fos = new FileOutputStream("Example.java");
- int i = 0;
- while ((i = fis.read()) != -1) {
- fos.write((byte) i);
- }
- fis.close();
- }
- }
In the example, mentioned above, we are reading the data of Simple.java file and write it into Example.java file.
Summary
Thus, we learnt that Java FileInputStream and FileOutputStream classes are used in Java file handling and also learnt how we can use these classes in Java.