Java provides the standard I/O facilities for reading text from either the file or the keyboard on the command line. The Reader class is used for this purpose that is available in the java.io package. It acts as an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). The Reader class is further categorized into the subclasses.
The following diagram shows a class-hierarchy of the java.io.Reader class.
However, most subclasses override some of the methods in order to provide higher efficiency, additional functionality, or both.
An InputStreamReader is a bridge from byte streams to character streams i.e. it reads bytes and decodes them into Unicode characters according to a particular platform. Thus, this class reads characters from a byte input stream. When you create an InputStreamReader, you specify an InputStream from which, the InputStreamReader reads the bytes.
The syntax of InputStreamReader is written as :
InputStreamReader<variable_name>= new InputStreamReader (System.in)
The BufferedReader class is the subclass of the Reader class. It reads character-input stream data from a memory area known as a buffer maintains state. The buffer size may be specified, or the default size may be used that is large enough for text reading purposes.
BufferedReader converts an unbuffered stream into a buffered stream using the wrapping expression, where the unbuffered stream object is passed to the constructor for a buffered stream class.
For example the constructors of the BufferedReader class shown as :
BufferedReader class provides some standard methods to perform specific reading operations shown in the table. All methods throw an IOException, if an I/O error occurs.
Method | Return Type | Description |
---|---|---|
read( ) | int | Reads a single character |
read(char[ ] cbuf, int off, int len) | int | Read characters into a portion of an array. |
readLine( ) | String | Read a line of text. A line is considered to be terminated by ('\n'). |
close( ) | void | Closes the opened stream. |
This program illustrates use of standard input stream to read the user input.
import java.io.*; public class ReadStandardIO { public static void main(String[] args) throws IOException { InputStreamReader inp = new InputStreamReader(System.in) BufferedReader br = new BufferedReader(inp); System.out.println("Enter text : "); String str = in.readLine(); System.out.println("You entered String : "); System.out.println(str); } } // Output of the Program: C:\>javac ReadStandardIO.java C:\>java ReadStandardIO Enter text: this is an Input Stream You entered String: this is an Input Stream C:\>
The streams provide a simple model for reading and writing data. However, streams don't support all the operations that are common with a disk file. Now, we will learn how to work with a file using the non-stream file I/O.
The File class deals with the machine dependent files in a machine-independent manner i.e. it is easier to write platformindependent code that examines and manipulates files using the File class. This class is available in the java.lang package.
The java.io.File is the central class that works with files and directories. The instance of this class represents the name of a file or directory on the host file system.
When a File object is created, the system doesn't check to the existence of a corresponding file/directory. If the files exist, a program can examine its attributes and perform various operations on the file, such as renaming it, deleting it, reading from or writing to it.
The constructors of the File class are shown in the table :
Constructor | Description |
---|---|
File(path) | Create File object for default directory (usually where program is located). |
File(dirpath,fname) | Create File object for directory path given as string. |
File(dir, fname) | Create File object for directory. |
Thus the statement can be written as :
File f = new File (“<filename>”);
The methods that are used with the file object to get the attribute of a corresponding file shown in the table.
Method | Description |
---|---|
f.exists() | Returns true if file exists. |
f.isFile() | Returns true if this is a normal file. |
f.isDirectory() | true if "f" is a directory. |
f.getName() | Returns name of the file or directory. |
f.isHidden() | Returns true if file is hidden. |
f.lastModified() | Returns time of last modification. |
f.length() | Returns number of bytes in file. |
f.getPath() | Path name. |
f.delete() | Deletes the file. |
f.renameTo(f2) | Renames f to File f2. Returns true if successful. |
f.createNewFile() | Creates a file and may throw IOException. |
Whenever the data is needed to be stored, a file is used to store the data. File is a collection of stored information that is arranged in string, rows, columns and lines etc. Further, we will see how to create a file. This example takes the file name and text data for storing to the file.
For creating a new file File.createNewFile ( ) method is used. This method returns a boolean value true if the file is created otherwise return false. If the mentioned file for the specified directory is already exist then the createNewFile () method returns the false otherwise the method creates the mentioned file and return true.
Let’s see an example that checks the existence of a specified file.
import java.io.*; public class CreateFile1 { public static void main(String[] args) throws IOException { File f; f=new File ("myfile.txt"); if(!f.exists()){ f.createNewFile(); System.out.println("New file \"myfile.txt\" has been created to the current directory"); } } } /* OUTPUT First, this program checks, the specified file "myfile.txt" is exist or not. If it does not exist then a new file is created with same name to the current location. Output of the Program C:\>javac CreateFile1.java C:\>java CreateFile1 New file "myfile.txt" has been created to the current directory C:\> */
If you try to run this program again then after checking the existence of the file, it will not be created and you will see a message as shown in the output.
C:\>javac CreateFile1.java C:\>java CreateFile1 the specified file is already exist C:\>
In Java, it is possible to set dynamic path, which is helpful for mapping local file name with the actual path of the file using the constructing filename path technique.
As seen, how a file is created to the current directory where the program is run. Now we will see how the same program constructs a File object from a more complicated file name, using the static constant File.separator or File.separatorCharto specify the file name in a platform-independent way. If we are using Windows platform then the value of this separator is ‘ \ ’.
Let’s see an example to create a file to the specified location.
import java.io.*; public class PathFile { public static void main(String[] args) throws IOException { File f; f=new File ("example" + File.separator + "myfile.txt"); f.createNewFile (); System.out.println ("New file \"myfile.txt\" has been created to the specified location"); System.out.println ("The absolute path of the file is: " +f.getAbsolutePath ()); } } // Output of the program: C:\>javac PathFile.java C:\>java PathFile New file "myfile.txt" has been created to the specified location the absolute path of the file is: C:\admin\example\myfile.txt C:\>
All Rights Reserved. © 2024 BookOfNetwork