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:
- Using Java
Scanner class (Basic level)
- Using Java
BufferedReader class (Intermediate level)
- 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:
- 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:
- InputStreamReader obj1 = new InputStreamReader(System.in);
-
- 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:
- 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
- import java.awt.Desktop;
- import java.io.*;
- public class OpenFileExample1
- {
- public static void main(String[] args)
- {
- try
- {
- //constructor of file class having file as argument
- File file = new File("C:\\demo\\demofile.txt");
- if(!Desktop.isDesktopSupported())//check if Desktop is supported by Platform or not
- {
- System.out.println("not supported");
- return;
- }
- Desktop desktop = Desktop.getDesktop();
- if(file.exists()) //checks file exists or not
- desktop.open(file); //opens the specified file
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }
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
- 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.
- // import java IO package
- import java.io.*;
- //import java utill package
- import java.util.*;
- public class FileOutputStreamcloseExample1 {
- // java program for close FileOutputStream
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- // creating FileInputStream
- FileInputStream fin= null;
- // creating new file output stream
- FileOutputStream fout= null;
- File file=null;
- Scanner sc;
- try {
- //
- file = new File ("Fos.txt");
- file.createNewFile();
- sc=new Scanner (System.in);
- System.out.println("Enter a string insert into JavaTpoint txt file ------->");
- fout= new FileOutputStream(file);
- //takes an input and covert it into char array.
- char st[] = sc.nextLine().toCharArray();
- for (int i=0; i<st.length;i++)
- {//write a string into the FOs.txt file
- fout.write(st[i]);
- }
- fin= new FileInputStream(file);
- int read;
- // read a string from the Fos.txt file.
- while((read=fin.read())!=-1)
- {
- System.out.print((char)read);
- }
- // releases FileOutputStream resources from the streams
- fout.close();
- }
- catch(Exception e)
- {
- System.out.println(e);
- }}}
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
- public final class Scanner
- extends Object
- 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:
- 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:
- 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.
- import java.util.*;
- public class ScannerExample {
- public static void main(String args[]){
- Scanner in = new Scanner(System.in);
- System.out.print("Enter your name: ");
- String name = in.nextLine();
- System.out.println("Name is: " + name);
- in.close();
- }
- }
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
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
- import java.io.IOException;
- import java.io.RandomAccessFile;
-
- public class RandomAccessFileExample {
- static final String FILEPATH ="myFile.TXT";
- public static void main(String[] args) {
- try {
- System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
- writeToFile(FILEPATH, "I love my country and my people", 31);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static byte[] readFromFile(String filePath, int position, int size)
- throws IOException {
- RandomAccessFile file = new RandomAccessFile(filePath, "r");
- file.seek(position);
- byte[] bytes = new byte[size];
- file.read(bytes);
- file.close();
- return bytes;
- }
- private static void writeToFile(String filePath, String data, int position)
- throws IOException {
- RandomAccessFile file = new RandomAccessFile(filePath, "rw");
- file.seek(position);
- file.write(data.getBytes());
- file.close();
- }
- }
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