+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
Â
Chapter 6
1. CHAPTER 6 FILES AND STREAMS
By
Sirage Zeynu (M.Tech)
School of Computing
2. 13-04-2021 Files and Streams 2
Streams
ï A stream is a sequence of data. A program uses an input stream to
read data from a source, one item at a time:
ï A stream is an abstraction that either produces or consumes.
ï Streams support many different kinds of data
simple bytes, primitive data types, localized characters, and
objects
ï Thus, the same I/O classes and methods can be applied to any type
of device. This means that an input stream can abstract many
different kinds of input: from a disk file, a keyboard, or a network
socket.
I/O Basics
3. 13-04-2021 Files and Streams 3
ï An I/O Stream represents an input source or an output destination.
ï A stream can represent many different kinds of sources and destinations,
including disk files, devices, other programs, and memory arrays.
ï Streams support many different kinds of data, including simple bytes,
primitive data types, localized characters, and objects. Some streams
simply pass on data; others manipulate and transform the data in useful
ways.
ï No matter how they work internally, all streams present the same simple
model to programs that use them
ï Streams are a clean way to deal with input/output without having every
part of your code understands the difference between a keyboard and a
network, for example. Java implements streams within class hierarchies
defined in the java.io package.
Input and Output Streams(1)
4. 13-04-2021 Files and Streams 4
Input and Output Streams(2)
A program uses an input stream to read data
from a source, one item at a time
5. 13-04-2021 Files and Streams 5
ï A program uses an output stream to write data to a destination,
one item at time
Input and Output Streams(3)
6. 13-04-2021 Files and Streams 6
Input and Output Streams(4)
input (sources) streams
Can read from these streams Root classes of all input streams:
âą The InputStream Class
âą The Reader Class
Output or sink (destination) streams
Can write to these streams Root classes of all output streams:
âą The OutputStream Class
âą The Writer Class
7. 13-04-2021 Files and Streams 7
Byte streams are defined by using two class hierarchies.
ï At the top are two abstract classes: InputStream and OutputStream.
Each of these abstract classes has several concrete subclasses that
handle the differences between various devices, such as disk files,
network connections, and even memory buffers.
ï The abstract classes InputStream and OutputStream define several
key methods that the other stream classes implement. Two of the
most important are read() and write(), which, respectively, read and
write bytes of data.
ï Both methods are declared as abstract inside InputStream and
OutputStream. They are overridden by derived stream classes.
Byte Streams and Character Streams(1)
8. 13-04-2021 Files and Streams 8
ï Programs use byte streams to perform input and output of 8-
bit bytes.
ï All byte stream classes are descended from InputStream and
OutputStream
ï There are many byte stream classes.
ï To demonstrate how byte streams work, we'll focus on
the file IO byte streams, FileInputStream and FileOutputStream
ï Other kinds of byte streams are used in much the same way;
they differ mainly in the way they are constructed.
9. 13-04-2021 Files and Streams 9
ï The Java platform stores character values using Unicode conventions.
ï Character stream I/O automatically translates this internal format to and
from the local character set.
ï In Western locales, the local character set is usually an 8-bit superset of
ASCII.
ï For most applications, I/O with character streams is no more complicated
than I/O with byte streams.
ï Input and output done with stream classes automatically translates to and
from the local character set.
ï A program that uses character streams in place of byte streams
automatically adapts to the local character set and is ready for
internationalization
Character Streams
10. 13-04-2021 Files and Streams 10
ï Byte streams
For binary data
Root classes for byte streams:
â The InputStream Class
â The OutputStream Class
â Both classes are abstract
Byte Streams and Character Streams(2)
Character streams
For Unicode characters
Root classes for character
streams:
â The Reader class
â The Writer class
â Both classes are abstract
13. 13-04-2021 Files and Streams 13
ï System contains three predefined stream variables, in, out, and err.
ï These fields are declared as public and static within System. This means
that they can be used by any other part of your program and without
reference to a specific System object.
ï System.out refers to the standard output stream. By default, this is the
console.
ï System.in refers to standard input, which is the keyboard by default.
System.err refers to the standard error stream, which also is the console by
default.
ï However, these streams may be redirected to any compatible I/O device.
ï System.in is an object of type InputStream; System.out and System.err are
objects of type PrintStream.
ï These are byte streams, even though they typically are used to read and
write characters from and to the console.
The Predefined Streams
14. 13-04-2021 Files and Streams 14
ï In Java, console input is accomplished by reading from
System.in
ï To obtain a character- based stream that is attached to the
console, you wrap System.in
ï in a BufferedReader object, to create a character stream.
ï BuffereredReader supports a buffered input stream. Its most
commonly used constructor is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of
BufferedReader that is being created.
Reading Console Input
16. 13-04-2021 Files and Streams 16
ï To read a string from the keyboard, use the version of
readLine() that is a member of the BufferedReader class.
Its general form is shown here:
ï String readLine() throws IOException As you can see, it
returns a String object.
ï The following program demonstrates BufferedReader and the
readLine() method; the program reads and displays lines of
text until you enter the word âstopâ:
Reading Strings
18. 13-04-2021 Files and Streams 18
ï Console output is most easily accomplished with print() and
println()
ï These methods are defined by the class PrintStream (which is
the type of the object referenced by System.out).
ï Even though System.out is a byte stream, using it for simple
program output is still acceptable.
ï Because PrintStream is an output stream derived from
OutputStream, it also implements the low-level method write().
Thus, write() can be used to write to the console.
ï The simplest form of write() defined by PrintStream is shown
here:
Writing Console Output
19. 13-04-2021 Files and Streams 19
void write(int byteval)
This method writes to the stream the byte specified by byteval.
Although byteval is declared as an integer, only the low-order
eight bits are written. Here is a short example that uses write()
to output the character âAâ followed by a newline to the screen:
You will not often use write() to perform console output (although doing so might be useful in some situations),
because print() and println() are substantially easier to use.
20. 13-04-2021 Files and Streams 20
The streams used most often are the standard input (the
keyboard) and the standard output (the CRT display).
Alternatively, standard input can arrive from a disk file using
"input redirection", and standard output can be written to a disk
file using "output redirection".
A more flexible mechanism to read or write disk files is
available through Java's file streams.
File Streams(1)
21. 13-04-2021 Files and Streams 21
The two file streams presented here are
The file reader stream
The file writer stream.
ï As with the standard I/O streams, we access these through objects
of the associated class,
ï namely the FileReader class and the FileWriter class. Unlike the
standard I/O streams, however, we must explicitly "open" a file
stream before using it.
ï After using a file stream, it is good practice to "close" the stream,
although, strictly speaking, this is not necessary as all streams are
automatically closed when a program terminates.
File Streams(2)
22. 13-04-2021 Files and Streams 22
ï To open a file output stream to which text can be written, we
use the FileWriter class.
ï As always, it is best to buffer the output. The following sets up
a buffered file writer stream named outFile to write text into a
file named save.txt:
Writing Files
PrintWriter outFile = new PrintWriter(new BufferedWriter(new FileWriter("save.txt"));
The object outFile, above, is of the PrintWriter class, just like System.out.
If a string, s, contains some text, it is written to the file as follows:
outFile.println(s);
When finished, the file is closed as expected:
outFile.close();
23. 13-04-2021 Files and Streams 23
ï FileWriter is useful to create a file writing characters into it.
ï This class inherits from the OutputStream class.
ï The constructors of this class assume that the default
character encoding and the default byte-buffer size are
acceptable.
ï To specify these values yourself, construct an
OutputStreamWriter on a FileOutputStream.
ï FileWriter is meant for writing streams of characters.
ï For writing streams of raw bytes, consider using a
FileOutputStream.
ï FileWriter creates the output file , if it is not present already.
FileWriter
24. 13-04-2021 Files and Streams 24
ï FileWriter(File file) â Constructs a FileWriter object given a File object.
ï FileWriter (File file, boolean append) â constructs a FileWriter object
given a File object.
ï FileWriter (FileDescriptor fd) â constructs a FileWriter object associated
with a file descriptor.
ï FileWriter (String fileName) â constructs a FileWriter object given a file
name.
ï FileWriter (String fileName, Boolean append) â Constructs a FileWriter
object given a file name with a Boolean indicating whether or not to
append the data written.
ï
Constructors
25. 13-04-2021 Files and Streams 25
public void write (char c) throws IOException â Writes a single
character.
ï public void write (char [] str) throws IOException â Writes an array
of characters.
ï public void write(String str)throws IOException â Writes a string.
ï public void write(String str,int off,int len)throws IOException â
Writes a portion of a string. Here off is offset from which to start
writing characters and len is number of character to write.
ï public void flush() throws IOException flushes the stream
ï public void close() throws IOException flushes the stream first and
then closes the writer.
Methods
26. 13-04-2021 Files and Streams 26
Following program depicts how to create a text file using FileWriter
27. 13-04-2021 Files and Streams 27
ï Let's begin with the FileReader class.
As with keyboard input, it is most efficient to work through the
BufferedReader
If we wish to read text from a file named foo.txt, it is opened as a
file input stream as follows:
The line above "opens" foo.txt as a FileReader object and passes it
to the constructor of the BufferedReader class.
The result is a BufferedReader object named inputFile.
Reading Files
BufferedReader inputFile = new BufferedReader(new FileReader(âfoo.txtâ))
28. 13-04-2021 Files and Streams 28
ï FileReader is useful to read data in the form of characters from
a âtextâ file.
ï This class inherit from the InputStreamReader Class.
ï The constructors of this class assume that the default character
encoding and the default byte-buffer size are appropriate.
ï To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
ï FileReader is meant for reading streams of characters.
ï For reading streams of raw bytes, consider using a
FileInputStream.
FileReader
29. 13-04-2021 Files and Streams 29
ï FileReader(File file) â Creates a FileReader , given the File
to read from
ï FileReader(FileDescripter fd) â Creates a new FileReader ,
given the FileDescripter to read from
ï FileReader(String fileName) â Creates a new FileReader ,
given the name of the file to read from
Constructors
30. 13-04-2021 Files and Streams 30
ï public int read () throws IOException â Reads a single character. This
method will block until a character is available, an I/O error occurs, or the
end of the stream is reached.
ï public int read(char[] cbuff) throws IOException â Reads characters
into an array. This method will block until some input is available, an I/O
error occurs, or the end of the stream is reached.
ï public abstract int read(char[] buff, int off, int len) throws
IOException âReads characters into a portion of an array. This method
will block until some input is available, an I/O error occurs, or the end of
the stream is reached.
public void close() throws IOException closes the reader.
ï public long skip(long n) throws IOException âSkips characters. This
method will block until some characters are available, an I/O error occurs,
or the end of the stream is reached.
Methods:
31. 13-04-2021 Files and Streams 31
Following program depicts how to read from the âtextâ file using FileReader
32. 13-04-2021 Files and Streams 32
a simple Java program to open a text file called temp.txt and to count the number of lines and characters in the
file.
33. 13-04-2021 Files and Streams 33
ï There are several ways to read a plain text file in Java
e.g. you can use FileReader, BufferedReader or Scanner to read
a text file.
ï Every utility provides something special
e.g. BufferedReader provides buffering of data for fast reading,
and Scanner provides parsing ability.
ï We can also use both BufferReader and Scanner to read a text
file line by line in Java.
Different ways of Reading a text file in Java
34. 13-04-2021 Files and Streams 34
1. Using FileReader class: Convenience class for reading
character files. The constructors of this class assume that the
default character encoding and the default byte-buffer size are
appropriate.
Constructors defined in this class are:
// Creates a new FileReader, given the File to read from. FileReader(File file)
// Creates a new FileReader, given the FileDescriptor to read from.
FileReader(FileDescriptor fd)
// Creates a new FileReader, given the name of the file to read from. FileReader(String
fileName)
Here are some of the many ways of reading files(1)
35. 13-04-2021 Files and Streams 35
Java Program to illustrate reading from FileReader using FileReader
36. 13-04-2021 Files and Streams 36
2. Using BufferedReader: This method reads text from a
character-input stream.
It does buffering for efficient reading of characters, arrays, and
lines.
The buffer size may be specified, or the default size may be used.
The default is large enough for most purposes.
ï In general, each read request made of a Reader causes a
corresponding read request to be made of the underlying
character or byte stream.
For example,
BufferedReader in = new BufferedReader(Reader in, int size);
Here are some of the many ways of reading files(2)
37. 13-04-2021 Files and Streams 37
Java Program to illustrate reading from FileReader using BufferedReader
38. 13-04-2021 Files and Streams 38
3. Using Scanner class: A simple text scanner which can parse
primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may
then be converted into values of different types using the
various next methods.
Here are some of the many ways of reading files(3)
39. 13-04-2021 Files and Streams 39
Java Program to illustrate reading from Text File using Scanner Class
40. 13-04-2021 Files and Streams 40
Java provides functions to move files between directories. Two
ways to achieve this are described here.
The first method utilizes Files package for moving while the
other method first copies the file to destination and then deletes
the original copy from the source.
Moving a file from one directory to another using Java
41. 13-04-2021 Files and Streams 41
ï Renaming and moving the file permanently to a new location.
Syntax:
ï public static Path move(Path source, Path target,
CopyOption..options) throws IOException
Parameters:
ï source - the path to the file to move
ï target - the path to the target file (may be associated with a
different provider to the source path)
ï options - options specifying how the move should be done
Returns: the path to the target file
1. Using Files.Path move() method:
43. 13-04-2021 Files and Streams 43
ï Copying the file and deleting the original file using these two
methods.
Syntax of renameTo():
ï public boolean renameTo(File dest)
ï Description: Renames the file denoted by this abstract path
name.
ï Parameters: dest - The new abstract path name for the
named file
ï Returns: true if and only if the renaming succeeded; false
otherwise
ï public boolean delete() Deletes the file or directory denoted
by this abstract path name.
2. Using Java.io.File.renameTo() and Java.io.File.delete() methods:
44. 13-04-2021 Files and Streams 44
Java program to illustrate Copying the file and deleting the original file
Reading Console Input
In Java, console input is accomplished by reading from System.in. To obtain a character- based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BuffereredReader supports a buffered input stream. Its most commonly used constructor is shown here:
BufferedReader(Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream) Because System.in refers to an object of type InputStream, it can be used for
inputStream. Putting it all together, the following line of code creates a BufferedReader that is
connected to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); After this statement executes, br is a character-based stream that is linked to the console
through System.in. Reading Characters
To read a character from a BufferedReader, use read(). The version of read() that we will be using is
int read( ) throws IOExceptionEach time that read() is called, it reads a character from the input stream and returns it as an
integer value. It returns â1 when the end of the stream is encountered. As you can see, it can throw an IOException.
Reading and writing take place character by character, which increases the number of I/O operations and effects performance of the system.BufferedWriter can be used along with FileWriter to improve speed of execution