text-based application.pptx
TRANSCRIPT
-
8/11/2019 Text-based application.pptx
1/52
Prepared By:Mr. Richard R. BasilioBSECE Dip ICT
-
8/11/2019 Text-based application.pptx
2/52
At the end of the lesson, the student shouldbe 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.
-
8/11/2019 Text-based application.pptx
3/52
Reading characters from the keyboard.
Use the System.in byte stream warped in a
BufferedReader object;
Use read method of the BufferedReader object
-
8/11/2019 Text-based application.pptx
4/52
-
8/11/2019 Text-based application.pptx
5/52
Reading an entire line
Use the System.in byte stream warped in a
BufferedReader object;
Use the readLine method;
-
8/11/2019 Text-based application.pptx
6/52
-
8/11/2019 Text-based application.pptx
7/52
-
8/11/2019 Text-based application.pptx
8/52
Dont forget to import thejava.io package asshown below:
Reading from streams may cause checkedexceptions to occur
Handle these exceptions using try-catch
statements
Or handle by indicating the exception in the
throws clause of the method
-
8/11/2019 Text-based application.pptx
9/52
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 theObject class.
-
8/11/2019 Text-based application.pptx
10/52
The class java.io.File can represent either afileor a directory.
Any program that uses the File class must importthis from the java.io package.
The simplest way is to include the whole package
using the statement:
import java.io.*;
-
8/11/2019 Text-based application.pptx
11/52
A File object is constructed by a program andused 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)
-
8/11/2019 Text-based application.pptx
12/52
Example:File file = new File("in.txt");
File myFile = new File("C:\\Users\\in.txt);
-
8/11/2019 Text-based application.pptx
13/52
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 existsString getName() Returns the files name
String getPath() Returns the files path
String getParent() Returns the name of the folder in which thefile 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 beused only for comparison with other files
times, and not as an absolute time
-
8/11/2019 Text-based application.pptx
14/52
-
8/11/2019 Text-based application.pptx
15/52
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.
-
8/11/2019 Text-based application.pptx
16/52
A streamis 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 coveredlater).
-
8/11/2019 Text-based application.pptx
17/52
Two types of streams:
Input stream - comprises of data flowing into a
program. Output stream - comprises of data flowing out of
a program.
-
8/11/2019 Text-based application.pptx
18/52
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 isavailable from the Java program.
Close the stream.
-
8/11/2019 Text-based application.pptx
19/52
Open an input/output stream associated witha physical device (e.g., file, network,
console/keyboard), by constructing anappropriate IO-stream object. Read from the opened input stream until
"end-of-stream" encountered, or write to theopened output stream (optionally flush thebuffered output).
Close the input/output stream.
-
8/11/2019 Text-based application.pptx
20/52
Java's IO operations is more complicatedthan 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.
-
8/11/2019 Text-based application.pptx
21/52
-
8/11/2019 Text-based application.pptx
22/52
Byte streams can be used to read or writebytes serially from an external device.
All the byte streams are derived from the abstractsuperclass InputStream and OutputStream, asillustrated in the class diagram.
-
8/11/2019 Text-based application.pptx
23/52
The abstract superclass InputStreamdeclares an abstract method read() to readone data-byte from the input source, andconvert the unsigned byte value (of 0 to 255)to an int. The read() method will blockuntil a byte is
available, an I/O error occurs, or the "end ofstream" is reached.
It returns -1 if for "end of stream", and throws anIOException if it encounters an I/O error.
-
8/11/2019 Text-based application.pptx
24/52
Similar to the input counterpart, the abstractsuperclass OutputStreamdeclares an
abstract method write() to write a data-byteto 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
-
8/11/2019 Text-based application.pptx
25/52
Both the InputStream and the OutputStream provides aclose() method to close the stream, which performs thenecessary 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 andFileOutputStream) to establish a connection to a physicaldevice (such as file, network, keyboard/console).
-
8/11/2019 Text-based application.pptx
26/52
-
8/11/2019 Text-based application.pptx
27/52
The IO streams are often layered or chainedwith 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.
-
8/11/2019 Text-based application.pptx
28/52
FileInputStream and FileOutputStream areconcrete implementation to the abstract
class of InputStream and OutputStream, tosupportFile IO. BufferedInputStream &
BufferedOutputStream is commonly appliedto speedup the IO operations.
-
8/11/2019 Text-based application.pptx
29/52
The DataInputStream andDataOutputStream can be stacked on top of
any InputStream and OutputStream to filterthe streams so as to perform I/O operationsin the desired data format, such as int anddouble
DataInputStream in = new DataInputStream(new BufferedInputStream( new
FileInputStream("in.txt")));
-
8/11/2019 Text-based application.pptx
30/52
-
8/11/2019 Text-based application.pptx
31/52
Output for the classByteStreamCopyWithOutBuffering
-
8/11/2019 Text-based application.pptx
32/52
-
8/11/2019 Text-based application.pptx
33/52
Output for the classByteStreamCopyWithBuffering
-
8/11/2019 Text-based application.pptx
34/52
-
8/11/2019 Text-based application.pptx
35/52
Java uses 16-bit character set internally,instead of 8-bit character set.
Hence, it has to differentiate between byte-basedIO (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.
-
8/11/2019 Text-based application.pptx
36/52
The abstract superclass Readeroperates oncharacters (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.
-
8/11/2019 Text-based application.pptx
37/52
Examples:
public abstract int read() throws IOException
public int read(byte[] bytesBuffer, int offset, intlength) throws IOException
public int read(byte[] bytesBuffer) throws
IOException
-
8/11/2019 Text-based application.pptx
38/52
The abstract superclass Writersimilarlydeclares 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
-
8/11/2019 Text-based application.pptx
39/52
-
8/11/2019 Text-based application.pptx
40/52
-
8/11/2019 Text-based application.pptx
41/52
The class RandomAccessFileprovidessupports for non-sequential, direct (or
random) access to a disk file. RandomAccessFile is a two-way stream,
supporting both input and output operationswithin the same stream.
-
8/11/2019 Text-based application.pptx
42/52
RandomAccessFile can be treated as a hugebyte array.
You can use a file pointer (of type long), similar toarray index, to access individual byte or group ofbytes in primitive types (such as int and double).
The file pointer is located at 0 when the file is
opened.
-
8/11/2019 Text-based application.pptx
43/52
It advances automatically for every read and writeoperation by the number of bytes processed.
-
8/11/2019 Text-based application.pptx
44/52
Thejava.io package contains aRandomAccessFile 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 followinginterfaces:
DataOutput
DataInput
-
8/11/2019 Text-based application.pptx
45/52
In constructing a RandomAccessFile, you canuse flags 'r' or 'rw' to indicate whether the file
is "read-only" or "read-write" access, Example:
RandomAccessFile f1 = newRandomAccessFile("filename", "r");
RandomAccessFile f2 = newRandomAccessFile("filename", "rw");
-
8/11/2019 Text-based application.pptx
46/52
METHOD PURPOSEpublic void seek(long pos) Position the file pointer for
subsequent read/write operation.
public int skipBytes(intbytes)
Move the file pointer forward by thespecified number of bytes.
public long getFilePointer() Obtain the position of the current
file pointer, in bytes, from thebeginning of the file.
public long length() Returns the length of the randomaccess file.
-
8/11/2019 Text-based application.pptx
47/52
-
8/11/2019 Text-based application.pptx
48/52
-
8/11/2019 Text-based application.pptx
49/52
Create a Java program using the concept ofFile Handling for STI Students Class Card
Evaluation System. The system can acceptstudents information, course and the fourperiodical grades and automaticallycomputes for the GWA. Save the information
in a text file with a file name of student.txtand display all students via reports. Followthe given sample output.
-
8/11/2019 Text-based application.pptx
50/52
REQUIREMENTS:
Use Character stream IOfor writing the data into
the textfile and Byte stream IOfor reading and
displaying the data into the console.
Use Scanner Class in entering values from
keyboard.
Add Exception handling for this exercise.
-
8/11/2019 Text-based application.pptx
51/52
-
8/11/2019 Text-based application.pptx
52/52