Unit 2 Oops
Unit 2 Oops
B.Tech CSE (2nd Year) (Dr. A.P.J. Abdul Kalam Technical University)
3.To read data from a file using FileInputStream, these steps you
need to follow :-
Step 1: Create an instance of the FileInputStream class and pass the path of the file that you
want to read as an argument to its constructor.
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.
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.
import java.io.*;
public class Write File Example {
public static void main(String[] args) {
try {
FileOutputStream fileOutput = new
FileOutputStream("file.txt");
String data ="This is some data that will be written to a file";
byte[] bytes = data.getBytes();
fileOutput.write(bytes);
In the example above, we create a FileOutputStream
fileOutput.close();
object write data to a file called "file.txt".
} catch (IOException e) {
e.printStackTrace();
We then create a string that contains some data that we
}
wants write to the file.
}
}
We convert this string to a byte array using the getbytes()
method and then we use the write() method to write the
data to the file.
Multithreading