Prepared By: Mr. Richard R. Basilio Bsece - Dip Ict
This document provides an overview of file handling in Java. It discusses using BufferedReader to read input from the keyboard and different IO streams. It explains the differences between character and byte streams. The key classes for file handling include File, BufferedReader, BufferedWriter, FileReader and FileWriter. The document also provides examples of reading, writing and manipulating files in Java.
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
54 views
Prepared By: Mr. Richard R. Basilio Bsece - Dip Ict
This document provides an overview of file handling in Java. It discusses using BufferedReader to read input from the keyboard and different IO streams. It explains the differences between character and byte streams. The key classes for file handling include File, BufferedReader, BufferedWriter, FileReader and FileWriter. The document also provides examples of reading, writing and manipulating files in Java.
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52
Prepared By:
Mr. Richard R. Basilio
BSECE Dip ICT At the end of the lesson, the student should be able to: Understand the concept of File Handling in Java. Use BufferedReader class for inputing data from keyboard. Identify the different IO Streams and apply it to a programming. Differentiate Character to Byte Streams IO.
Reading characters from the keyboard. Use the System.in byte stream warped in a BufferedReader object;
Use read method of the BufferedReader object
Reading an entire line Use the System.in byte stream warped in a BufferedReader object;
Use the readLine method;
Dont forget to import the java.io package as shown below:
Reading from streams may cause checked exceptions to occur Handle these exceptions using try-catch statements Or handle by indicating the exception in the throws clause of the method The file class does not provide any opening, processing, or closing capabilities for files but it is used to obtain information about the file, such as whether it exists or is open, its size, and its most recent modification date. The File class is a direct descendant of the Object class.
The class java.io.File can represent either a file or a directory. Any program that uses the File class must import this from the java.io package. The simplest way is to include the whole package using the statement: import java.io.*;
A File object is constructed by a program and used while it is running to manipulate a disk file and to get information about it. Constructors that can be used to create File object: File(String directoryPath) File(String directoryPath, String filename) File(File dirObj, String filename)
Example: File file = new File("in.txt"); File myFile = new File("C:\\Users\\in.txt);
METHOD PURPOSE boolean canRead() Returns true if a file is readable boolean canWrite() Returns true if a file is writable boolean exists() Returns true if a file exists String getName() Returns the files name String getPath() Returns the files path String getParent() Returns the name of the folder in which the file can be found long length() Returns the files size long lastModified() Returns the time the file was last modified; this time is system dependent and should be used only for comparison with other files times, and not as an absolute time
Programs read inputs from data sources (e.g., keyboard, file, network, or another program) and write outputs to data sinks (e.g., console, file, network, or another program). Inputs and outputs in Java are handled by the so-called stream.
A stream is a sequential and continuous one- way flow of information (just like water or oil flows through the pipe). All Java I/O streams are one-way (except the RandomAccessFile, which will be covered later).
Two types of streams: Input stream - comprises of data flowing into a program. Output stream - comprises of data flowing out of a program.
Basic steps for reading a stream: Open a stream from a data source to a Java program. Read the data while data is available from the data source. Close the stream. Basic steps for writing a stream: Open a stream from a Java program to a data source. Write the data to the data source while data is available from the Java program. Close the stream. Open an input/output stream associated with a physical device (e.g., file, network, console/keyboard), by constructing an appropriate IO-stream object. Read from the opened input stream until "end-of-stream" encountered, or write to the opened output stream (optionally flush the buffered output). Close the input/output stream.
Java's IO operations is more complicated than C/C++, as Java uses 16-bit character set (instead of 8-bit character set). As a consequence, it needs to differentiate between byte-based IO and character-based IO.
Byte streams can be used to read or write bytes serially from an external device. All the byte streams are derived from the abstract superclass InputStream and OutputStream, as illustrated in the class diagram.
The abstract superclass InputStream declares an abstract method read() to read one data-byte from the input source, and convert the unsigned byte value (of 0 to 255) to an int. The read() method will block until a byte is available, an I/O error occurs, or the "end of stream" is reached. It returns -1 if for "end of stream", and throws an IOException if it encounters an I/O error.
Similar to the input counterpart, the abstract superclass OutputStream declares an abstract method write() to write a data-byte to the output sink. Similar to the read(), two variations of the write() method to write a block of bytes from a byte- array buffer are implemented: public void write(byte[] bytesBuffer) throws IOException
Both the InputStream and the OutputStream provides a close() method to close the stream, which performs the necessary clean-up operations as well as frees the system resources. InputStream and OutputStream are abstract classes that cannot be instantiated. You need to choose an appropriate concrete implementation subclass (such as FileInputStream and FileOutputStream) to establish a connection to a physical device (such as file, network, keyboard/console).
The IO streams are often layered or chained with other IO steams, for purposes such as buffering, filtering or format conversion. For example, we can layer a BufferedInputStream to a FileInputStream for buffered input, and stack a DataInputStream in front for formatted data input, as illustrated in the following diagram.
FileInputStream and FileOutputStream are concrete implementation to the abstract class of InputStream and OutputStream, to support File IO. BufferedInputStream & BufferedOutputStream is commonly applied to speed up the IO operations.
The DataInputStream and DataOutputStream can be stacked on top of any InputStream and OutputStream to filter the streams so as to perform I/O operations in the desired data format, such as int and double DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream("in.txt")));
Output for the class ByteStreamCopyWithOutBuffering
Output for the class ByteStreamCopyWithBuffering
Java uses 16-bit character set internally, instead of 8-bit character set. Hence, it has to differentiate between byte-based IO (for binary data), and character-based text IO. Other than the unit of operation, character-based IO is almost identical to byte-based IO. Instead of InputStream and OutputStream, Reader and Writer shall be used for character- based IO.
The abstract superclass Reader operates on characters (primitive char or unsigned 16-bit integer from 0 to 65535), it similarly declares an abstract method read() to read one character from the input source, and convert the char to an int; and variations of read() to read a block of characters.
Examples: public abstract int read() throws IOException public int read(byte[] bytesBuffer, int offset, int length) throws IOException public int read(byte[] bytesBuffer) throws IOException
The abstract superclass Writer similarly declares an abstract method write(), to write a character to the output sink. public void abstract void write(int aChar) throws IOException public void write(byte[] bytesBuffer, int offset, int length) throws IOException public void write(byte[] bytesBuffer) throws IOException
The class RandomAccessFile provides supports for non-sequential, direct (or random) access to a disk file. RandomAccessFile is a two-way stream, supporting both input and output operations within the same stream.
RandomAccessFile can be treated as a huge byte array. You can use a file pointer (of type long), similar to array index, to access individual byte or group of bytes in primitive types (such as int and double). The file pointer is located at 0 when the file is opened.
It advances automatically for every read and write operation by the number of bytes processed.
The java.io package contains a RandomAccessFile class that is used to read from and write data to anywhere in a file. The RandomAccessFile extends from the Object class and inherits from the following interfaces: DataOutput DataInput
In constructing a RandomAccessFile, you can use flags 'r' or 'rw' to indicate whether the file is "read-only" or "read-write" access, Example: RandomAccessFile f1 = new RandomAccessFile("filename", "r"); RandomAccessFile f2 = new RandomAccessFile("filename", "rw");
METHOD PURPOSE public void seek(long pos) Position the file pointer for subsequent read/write operation. public int skipBytes(int bytes) Move the file pointer forward by the specified number of bytes. public long getFilePointer() Obtain the position of the current file pointer, in bytes, from the beginning of the file. public long length() Returns the length of the random access file.
Create a Java program using the concept of File Handling for STI Students Class Card Evaluation System. The system can accept students information, course and the four periodical grades and automatically computes for the GWA. Save the information in a text file with a file name of student.txt and display all students via reports. Follow the given sample output. REQUIREMENTS: Use Character stream IO for writing the data into the textfile and Byte stream IO for reading and displaying the data into the console. Use Scanner Class in entering values from keyboard. Add Exception handling for this exercise.