You need to write a Java program to copy GATE exam candidate names available in Candidates.txt file into a file named Candidates.xls. Let us see the operations involved in this program..
Such operations where a program needs to interact with external environments like files, database, I/O devices, etc. are called as Input/Output (I/O) operations.
In an I/O operation source and destination can be anything that holds, generates or consumes data, e.g. file system, application program, peripheral devices like keyboard, console, etc.
Java I/O API uses streams to perform I/O operations.
Reading From a File Using FileInputStream
You need to write a Java program to display the answers of a candidate available in Answers.txt file on the console. Here, Answers.txt file becomes the source for your program and console becomes the destination.
Look into the below sample code to display the content of Answers.txt on the console.
public class FileInputStreamTester{
public static void main(String[] args) {
InputStream fis=null;
try{
fis = new FileInputStream("Answers.txt"); //1. creates an instance of InputStream pointing the file in the given path
int data = fis.read(); // 2. reads first byte of data from the input stream.
while (data != -1){
System.out.print((char)data+" "); // prints the byte data on the console
data = fis.read(); // 2. reads next byte of data in a loop until EOF reached
}
} catch (IOException ioe) {
System.out.println("Error :"+ioe.getMessage());
} finally {
try{
if(fis!=null){
fis.close(); // 3. closes the FileInputStream
}
} catch (IOException ioe) {
System.out.println("Error :"+ioe.getMessage());
}
}
}
}
Below are the steps we used in the code.
Create an instance of InputStream
Read data byte by byte until end of file (EOF) is reached
Close the stream
Let us discuss these steps in detail.
Note: Since the code related I/O operations may throw an IOException, it is surrounded with try-catch-finally block.
Creating an Instance of InputStream
Java program needs an instance of InputStream for reading data from a file. For example, if your program needs to display the content of Answers.txt file on the console, then it requires an InputStream object.
You can use the below constructor to create an instance of FileInputStream.
FileInputStream(String filePath)
The argument filePath represents the path name of a file. Based on the location of a file the filePath can be either absolute or relative as shown below
s3
Note: You already know that FileInputStream is a subclass of InputStream and you also know that parent class reference variable can refer child class's object. So, it is absolutely fine to create a reference variable fis of type InputStream and make it to refer an object of type FileInputStream as shown in the code.
Reading Data Byte by Byte
The read() method of FileInputStream is used to read one byte of data at a time. The read() method reads the next byte from the input stream and returns it as an int. It returns -1 when end of file (EOF) is reached, that is, when there are no more data to be read.
int data = fis.read(); // reads a byte of data from the input stream
while (data != -1){
System.out.print((char)data+" "); // prints the data on the console
data = fis.read(); // reads the data in a loop
}
We can use available() method of FileInputStream as well to read the bytes in a loop as shown below. The available() method returns the number of bytes remaining to read.
while (fis.available()>0){ // checks the number of bytes remaining to read
data = fis.read(); // reads the data in a loop
System.out.print((char)data+" "); // prints the data in the console
}
Rather than reading one byte at a time, we can read array of bytes as well using
read(byte[] b) method of FileInputStream as shown below. This method reads and stores as many bytes as the size of byte array and returns an int indicating the number of bytes read. It returns -1 if EOF is reached.
byte [] byteArray = new byte[10]; //creates a byte array where the data read should be stored
if(fis.read(byteArray)>0){ //reads the data into the byte array and returns the number of bytes read
for(int i=0;i
Writing Into a File Using FileOutputStream
You need to write a Java program to write the answers of a candidate into a file named Answers.txt. Here, your program becomes the source to itself and Answers.txt file becomes the destination.
Look into the below sample code to write your data into Answers.txt file.
public class FileOutputStreamTester{
public static void main(String[] args) {
OutputStream fos=null;
try{
fos = new FileOutputStream("Answers.txt"); //1. creates an instance of OutputStream pointing the file in the given path
fos.write(65);
fos.write(67); //2. writes one byte of data into file
System.out.println("Data written successfully");
} catch (IOException ioe) {
System.err.println("Error :"+ioe.getMessage());
} finally {
try{
if(fos!=null){
fos.close(); //3. closes the FileOutputStream
}
} catch (IOException ioe) {
System.err.println("Error :"+ioe.getMessage());
}
}
}
}
Below are the steps we used in the code.
Create an instance of OutputStream
Write data byte by byte
Close the stream (As discussed while reading)
Let us discuss about first two steps in detail. The third step, close the stream, is same as closing the stream in FileInputStream. The close() method of that specific stream has to be invoked.
Creating an Instance of OutputStream
Java Program needs an instance of OutputStream for writing byte data into a file. For example, if your program needs to perform a write operation on a file named ‘Answers.txt', it requires an OutputStream object. Based on whether you want to overwrite or append into the given file, you can use either of the below constructors for object creation
The String property filePath represents the absolute or relative path of the file.
Note: Both the constructors can create a new file if the file is not available in the given path.
String company="Infosys";
byte [] byteArray = company.getBytes(); //converts String to byte array
fos.write(byteArray); //writes array of bytes into file
try-with-resources helps us to reduce the code size. It is an automatic resource management feature added in Java 7 which can close the resources automatically.
public class FileOutputStreamTester{
2 public static void main(String[] args){
3 try(OutputStream fos = new FileOutputStream("Answers.txt"))
4 {
5 fos.write(65);
6 System.out.println("Data written successfully");
7 }catch (IOException ioe) {
8 System.err.println("Error :"+ioe.getMessage());
9 }
10 }
11 }
Only the AutoCloseable objects, an object that implements java.lang.AutoCloseable interface, can be declared in try-with-resources. The AutoCloseable interface, which is introduced from Java 7, defines a single close() method. If an AutoCloseable object is declared in try block opening (resource specification header), the close() method of that object is called automatically when exiting a try-with-resources block.
try (FileInputstream inputStream = new FileInputstream("file1.txt");
FileOutputStream outputStream = new FileOutputStream("file2.txt")) {
// try block code
}
class src2dest
{
public static void main(String args[])
throws FileNotFoundException,IOException
{
/* If file doesnot exist FileInputStream throws
FileNotFoundException and read() write() throws
IOException if I/O error occurs */
FileInputStream fis = new FileInputStream(args[0]);
/* assuming that the file exists and need not to be
checked */
FileOutputStream fos = new FileOutputStream(args[1]);
int b;
while ((b=fis.read()) != -1)
fos.write(b);
/* read() will readonly next int so we used while
loop here in order to read upto end of file and
keep writing the read int into dest file */
fis.close();
fos.close();
}
}