Wednesday 3 January 2024

Unit 5: Using I/O | Java Programming | ICT. Ed 455 | BICTE | Fifth Semester | Bicte blog

 

Unit 5:

 Using I/O


5.1 Console and File I/O

5.2 Opening and closing files

5.3 Scanner class

5.4 Byte Streams and Character Streams

5.5 Reading and Writing Byte streams

5.6 Reading and writing character streams

5.7 Random Access Files

Practical work

1.       Write program to apply different input and output classes.

2.       Use various method for file I/O

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

We can perform file handling in Java by Java I/O API.

 

What is a Console?

The process of taking input from the console is introduced by the concept of Java Console. Java programming language provides several ways in order to take input from the console and provide its corresponding output on the same console.

There are three ways to take the input from the Java console. They are:

  1. Using Java Scanner class (Basic level)
  2. Using Java BufferedReader class (Intermediate level)
  3. Using Java Console class

Scanner class in Java

A class that is used to scan inputs within the program is known as the Scanner class. We use this class to take the input within the program by creating an abject in the Scanner class

Syntax of Scanner class:

  1. Scanner obj = new Scanner(System.in);  

Here, " Scanner " is considered as a class and " obj " is an object that is created within a class. So, in order to scan any input in the entire program, we can use this object that is created in the " Scanner " class.

BufferedReader class in Java:

It is one of the classical methods of taking input from the user ( sometimes by using a console also ). A new statement, " InputStreamReader " is also introduced along with the " BufferedReader " in order to scan the input values using BufferedReader. Syntax of BufferedReader class:

  1. InputStreamReader obj1 = new InputStreamReader(System.in);  
  2.   
  3. BufferedReader obj2 = new BufferedReader(obj1);  

Java Console class in Java

The class " Console " in Java was introduced from Java version 1.5 and was brought into charge from that version. It was one of the most anticipated usages in Java Programming language. The class " Console " can be accessed through the package " Java.io " which is the basic package that is used in all programs constructed in Java. There are several methods that are embedded within the " Console " class.

Java - Files and I/O

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc.

Stream

A stream can be defined as a sequence of data. There are two kinds of Streams −

·       InPutStream − The InputStream is used to read data from a source.

·       OutPutStream − The OutputStream is used for writing data to a destination.



Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic functionality related to streams and I/O. We will see the most commonly used examples one by one –

How to Open a File in Java

There are following ways to open a file in Java:

  • Java Desktop class
  • Java FileInputStream class
  • Java BufferedReader class
  • Java FileReader class
  • Java Scanner class
  • Java nio package

Java Desktop class

Java Desktop class provide an open() method to open a file. It belongs to a java.awt package. Desktop implementation is platform-dependent, so it is necessary to check the operating system supports Desktop or not. The Desktop class looks for an associated application registered on the native desktop to handle a file. If there is no associated application or application is fails to be launched, it throws the FileNotFoundException. Launches the user default browser to show a specified URI.

  • Launches the user default mail client with an optional mail-to URI.
  • Launches the registered application to open, edit, or print a specified file.

The open() method of Desktop class launches the associated application to open a file. It takes a file as an argument. The signature of the method is:

  1. public void open (File file) throws IOException  

The method throws the following exceptions:

  • NullPointerException: If the file is null.
  • IllegalArgumentException: It is thrown when the file does not exist.
  • IOException: It is thrown when there is no application associated with the given file type.
  • UnsupportedOperationExecution: If the current platform does not support the Desktop.Action.Open action.

Example

  1. import java.awt.Desktop;  
  2. import java.io.*;  
  3. public class OpenFileExample1   
  4. {  
  5. public static void main(String[] args)   
  6. {  
  7. try  
  8. {  
  9. //constructor of file class having file as argument  
  10. File file = new File("C:\\demo\\demofile.txt");   
  11. if(!Desktop.isDesktopSupported())//check if Desktop is supported by Platform or not  
  12. {  
  13. System.out.println("not supported");  
  14. return;  
  15. }  
  16. Desktop desktop = Desktop.getDesktop();  
  17. if(file.exists())         //checks file exists or not  
  18. desktop.open(file);              //opens the specified file  
  19. }  
  20. catch(Exception e)  
  21. {  
  22. e.printStackTrace();  
  23. }  
  24. }  
  25. }  

When we run the above program, it opens the specified text file in the default text editor. We can also open the .docx, .pdf, and .jpg file.

Output:


Java FileOutputStream close() Method

The close() method of FileOutputStream class is used to close the file output stream and releases all system resources associated with this stream.

Syntax

  1. public void close()  

Parameter

NA

Return Value

This method does not return any value.

Exception

NA

Example 1

Java Program to releases FileOutputStream resources from the streams.

  1. // import java IO package  
  2. import java.io.*;  
  3. //import java utill package  
  4. import java.util.*;  
  5. public class FileOutputStreamcloseExample1 {  
  6. // java program for close FileOutputStream  
  7.     public static void main(String[] args) {  
  8.         // TODO Auto-generated method stub  
  9.         // creating  FileInputStream  
  10.         FileInputStream fin= null;  
  11.         // creating new file output stream  
  12.         FileOutputStream fout= null;  
  13.         File file=null;  
  14.         Scanner sc;  
  15.         try {  
  16.             //  
  17.             file = new File ("Fos.txt");  
  18.              file.createNewFile();  
  19.            sc=new Scanner (System.in);  
  20.            System.out.println("Enter a string  insert into JavaTpoint txt file ------->");  
  21.            fout= new FileOutputStream(file);  
  22.            //takes an input and covert it into char array.  
  23.           char st[] = sc.nextLine().toCharArray();      
  24.          for (int i=0; i<st.length;i++)  
  25.          {//write  a string into the FOs.txt file  
  26.              fout.write(st[i]);  
  27.          }  
  28.          fin= new FileInputStream(file);  
  29.          int read;  
  30.          // read a string from the Fos.txt file.  
  31.          while((read=fin.read())!=-1)  
  32.          {  
  33.         System.out.print((char)read);  
  34.               }  
  35.       // releases FileOutputStream resources from the streams  
  36.          fout.close();      
  37.         }  
  38.         catch(Exception e)  
  39.         {  
  40.            System.out.println(e);          
  41.         }}}  

Output:

Enter a string  insert into JavaTpoint txt file ------->
ASHU BHATI.
 String that we are enter into the file----->
ASHU BHATI.

 

Java Scanner

Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc.

The Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0) method which returns a single character.

Java Scanner Class Declaration

  1. public final class Scanner  
  2.           extends Object  
  3.           implements Iterator<String>   

How to get Java Scanner

To get the instance of Java Scanner which reads input from the user, we need to pass the input stream (System.in) in the constructor of Scanner class. For Example:

  1. Scanner in = new Scanner(System.in);  

To get the instance of Java Scanner which parses the strings, we need to pass the strings in the constructor of Scanner class. For Example:

  1. Scanner in = new Scanner("Hello Javatpoint");  

Example 1

Let's see a simple example of Java Scanner where we are getting a single input from the user. Here, we are asking for a string through in.nextLine() method.

  1. import java.util.*;  
  2. public class ScannerExample {  
  3. public static void main(String args[]){  
  4.           Scanner in = new Scanner(System.in);  
  5.           System.out.print("Enter your name: ");  
  6.           String name = in.nextLine();  
  7.           System.out.println("Name is: " + name);             
  8.           in.close();             
  9.           }  
  10. }  

Output:

Enter your name: sonoo jaiswal
Name is: sonoo jaiswal

Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file −

Example

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class CopyFile {
 
   public static void main(String args[]) throws IOException {  
      FileInputStream in = null;
      FileOutputStream out = null;
 
      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

Now let's have a file input.txt with the following content −

This is test for copy file.

As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −

$javac CopyFile.java
$java CopyFile

Character Streams

Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file −

Example

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
public class CopyFile {
 
   public static void main(String args[]) throws IOException {
      FileReader in = null;
      FileWriter out = null;
 
      try {
         in = new FileReader("input.txt");
         out = new FileWriter("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

Now let's have a file input.txt with the following content −

This is test for copy file.

As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −

$javac CopyFile.java
$java CopyFile
 

Reading and Writing File stream

As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.


The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial.

FileInputStream

This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the file −

InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows −

File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.

FileOutputStream

FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the file −

OutputStream f = new FileOutputStream("C:/java/hello") 

Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows −

File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.

Reading and writing character streams:

Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file −

Example

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

 

public class CopyFile {

 

   public static void main(String args[]) throws IOException {

      FileReader in = null;

      FileWriter out = null;

 

      try {

         in = new FileReader("input.txt");

         out = new FileWriter("output.txt");

        

         int c;

         while ((c = in.read()) != -1) {

            out.write(c);

         }

      }finally {

         if (in != null) {

            in.close();

         }

         if (out != null) {

            out.close();

         }

      }

   }

}

Now let's have a file input.txt with the following content −

This is test for copy file.

As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −

$javac CopyFile.java

$java CopyFile

Java - RandomAccessFile

This class is used for reading and writing to random access file. A random access file behaves like a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor we do the read write operations. If end-of-file is reached before the desired number of byte has been read than EOFException is thrown. It is a type of IOException.

Constructor

Constructor

Description

RandomAccessFile(File file, String mode)

Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

RandomAccessFile(String name, String mode)

Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

 

Example

  1. import java.io.IOException;  
  2. import java.io.RandomAccessFile;  
  3.   
  4. public class RandomAccessFileExample {  
  5.     static final String FILEPATH ="myFile.TXT";  
  6.     public static void main(String[] args) {  
  7.         try {  
  8.             System.out.println(new String(readFromFile(FILEPATH, 018)));  
  9.             writeToFile(FILEPATH, "I love my country and my people"31);  
  10.         } catch (IOException e) {  
  11.             e.printStackTrace();  
  12.         }  
  13.     }  
  14.     private static byte[] readFromFile(String filePath, int position, int size)  
  15.             throws IOException {  
  16.         RandomAccessFile file = new RandomAccessFile(filePath, "r");  
  17.         file.seek(position);  
  18.         byte[] bytes = new byte[size];  
  19.         file.read(bytes);  
  20.         file.close();  
  21.         return bytes;  
  22.     }  
  23.     private static void writeToFile(String filePath, String data, int position)  
  24.             throws IOException {  
  25.         RandomAccessFile file = new RandomAccessFile(filePath, "rw");  
  26.         file.seek(position);  
  27.         file.write(data.getBytes());  
  28.         file.close();  
  29.     }  
  30. }  

The myFile.TXT contains text "This class is used for reading and writing to random access file."

after running the program it will contains

This class is used for reading I love my country and my peoplele.


No comments:

Post a Comment