Console I/O in Java 2
Files and File I/O:-
- The Java technology includes a rich set of I/O streams which are described in the previous section.
- In this it examines several simple technologies for reading and writing to files with a focus on the character data, including:
- Creating File Objects
- Manipulating File Objects
- Reading and Writing to file streams
Creating a New File Object:-
- The File class provides several utilities for handling files and obtaining information about them.
- In java technology, a directory is just another file. We can create a File object that represents a directory and then use it to the identify other files, as shown in 3rd bullet.
- File myFile;
myFile = new File(“myfile234.txt”);
- myFile = new File(“MyDocs”,”myfile234.txt”);
- File myDir = new File(“MyDocs”);
myFile = new File(“myDir”,”myfile234.txt”);
- The constructor that you often depends on the other file objects that you can access.
- For example, if you use only one file in your application, use the first constructor.
- However, if you use several files from a common directory, using the second or third constructors may be easier.
- The class File does define platform independent methods for manipulating a file maintained by a native file system.
- However, it does not permit you to access the contents of the file.
Note: – you can use a File object as the constructor arguments for FileReader and FileWriter objects in place of a string. This gives you independence from the local file system conventions and is recommended in general.
The File Tests and Utilities:-
- After you create a File object, you can use any methods in the following sections to gather information about the file.
File Names:-
The following method does return file names:
- String getName()
- String getPath()
- String getAbsolutePath()
- String getParent()
- String renameTo(File newName)
Directory Utilities:-
The following method does provide directory utilities:
- boolean mkdir()
- String [] list()
General File information and Utilities:-
The following methods return general file information:
- long longModified()
- long length()
- boolean delete()
File Tests:-
The following methods return information about file attributes:
- boolean exists()
- boolean canWrite()
- boolean canRead()
- boolean isFile()
- boolean isDirectory()
- boolean isAbsolute()
- boolean isHidden()
File Streams I/O:-
The java SE development Kit supports file input in two forms:
- Use a FileReader class to read characters
- Use a BufferedReader class to use the readLine method
The java SE development Kit supports file output in two forms:
- Use a FileWriter class to write characters
- Use a PrintWriter class to use the print and println methods
File Input Example:-
In thhe code given below reads a text file and echoes each line to standard output, which prints the file.
Reading from a File
- import java.io.*;
- public class ReadFile
- {
- public static void main(String[] args)
- {
- // create file
- File file = new File(args[0]);
- try{
- // create a buffered reader
- // to read each line from a file.
- BufferedReader in = new BufferedReader(new FileReader(file));
- String s;
- try{
- // read each line from the file
- s = in.readLine();
- while(s!=null)
- {
- System.out.println(“Read: ”+s);
- s = in.readLine();
- }
- }finally{
- // close the buffered reader
- in.close();
- }
- }catch(FileNotFoundException e1){
- // if this file does not exist
- System.err.println(“File not found: ”+file);
- }catch(IOException e2){
- // catch any other IO Exceptions.
- e2.printStackTrace();
- }
- }
- }
- }
- Line 7 creates a new File object based on the first command line argument to the program.
- Line 11 creates a buffered reader that wraps around a file reader. This code throws a FileNotFoundException if the file does not exist.
- The code after line 13 reads a text file and echoes each line to standard output, thus printing the file.
- In a given code, the while loop in Lines 16-20 is exactly the same as in the KeyboardInput program, it reads each text line in the buffered reader and echoes it to standard output.
- Line 23 closes the buffered reader, which in turn closes the file reader that the buffered reader object decorates.
- The exception handling code in Line 25-28 catches the FileNotFoundException that may be thrown by the FileReader constructor.
- Lines 28-31 handle any other I/O based exception that may be thrown (by the readLine and close methods).
File Output Example:-
The cod egiven below reads input lines from the keyboard and echoes each line to a file.
File Output Example
- import java.io.*;
- public class WriteFile
- {
- public static void main(String[] args)
- {
- // create file
- File file = new File(args[0]);
- try{
- // create a buffered reader
- InputStreamReader isn = new InputStreamReader(System.in);
- BufferedReader in = new BufferedReader(isr);
- // create a print writer on this file.
- PrintWriter out = new PrintWriter(new FileWriter(file));
- String s;
- System.out.println(“Enter file text. ”);
- System.out.println(“[type ctrl-d to stop.]”);
- // read each input line
- s = in.readLine();
- while(s!=null)
- {
- out.println(s);
- }
- // close the buffered reader
- in.close();
- out.close();
- }catch(IOException e){
- // catch any other IO Exceptions.
- e2.printStackTrace();
- }
- }
- }
- }
- Just as in code before, line 8creates a File object based on the first command line argument.
- Line 12 creates a character reader stream from the binary stream (System.in).
- Line 13 creates a buffered reader for the standard input. Line 15 creates a print writer that decorates a file writer for the created in Line 8.
- Lines 18-19 prompt the user to enter lines of text to be placed in the file and to type control-d stop.
- The Lines 23-26 read from the input stream and prints to the file, one line at a time.
Note: – the control-d character (which represents end of file) must be used in this example and not control-c, because control-c terminates the JVM before the program closes the file stream properly.
- Line 28 and line 29 close the input and output streams. Line 30-33 handles any I/O exceptions that may be thrown.
