0% found this document useful (0 votes)
8 views

advanced 2

advanced

Uploaded by

amentiabraham674
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

advanced 2

advanced

Uploaded by

amentiabraham674
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Mizan Tepi University

School of Computing and Informatics


Department of Software Engineering

Chapter 2: Streams and File I/O

1
Objectives
To elaborate files and streams

To discuss the differences between text files and binary


files.
To explain how creating, writing to and reading from files
are possible.

2
1. Introduction
Program often need to communicate with the outside world.

The means of communication are input (such as a keyboard)


and output (such as the computer screen).

Programs can also communicate through stored data, such


as files.

3
I/O Overview:
I/O = Input/Output

In this context it is input to and output from programs

Input can be from keyboard or a file

Output can be to display (screen) or a file

Advantages of file I/O


 Permanent copy

 Output from one program can be input to another

 Input can be automated (rather than entered manually)

 The data source and data destination can be anything that holds, generates, or
consumes data. Obviously this includes disk files, a peripheral device, a
network socket, or an array.
4
2. Files and Streams
Data stored in variables and arrays is temporary.

For long-term retention of data, even after the programs


that create the data terminate, computers use files.

You use files every day for tasks such as writing a


document or creating a spreadsheet.

Computers store files on secondary storage devices such as


hard disks, optical disks, flash drives and magnetic tapes.

Data maintained in files is persistent data—it exists beyond


5
the duration of program execution.
 Java views each file as a sequential stream of bytes.

 Every operating system provides a mechanism to determine the end of a file,


such as an end-of-file marker or a count of the total bytes in the file.

 A Java program processing a stream of bytes simply receives an indication from


the operating system when it reaches the end of the stream.

 The program does not need to know how the underlying platform represents
files or streams.

6
2.1 Types of Streams

 File streams can be used to input and output data as bytes or


characters.

 Byte-based streams input and output data in its binary format.

 Character-based streams input and output data as a sequence of


characters/unicode.

 If the value 5 were being stored using a byte-based stream, it would


be stored in the binary format of the numeric value 5, or 101.

 If the value 5 were being stored using a character-based stream, it


would be stored in the binary format of the character 5, or 00000000
00110101 (this is the binary representation for the numericvalue 53,
7 which indicates the Unicode® character 5).
 The difference between the two forms is that the numeric value
can be used as an integer in calculations, whereas the
character 5 is simply a character that can be used in a string of
text.

 Files that are created using byte-based streams are referred to


as binary files, while files created using character-based
streams are referred to as text files.

 Text files can be read by text editors, while binary files are
read by programs that understand the file’s specific content
and its ordering for changing to human readable format.

8
Binary Vs. Text Files:
 All data and programs are ultimately just zeros and ones
 Text files: the bits represent printable characters
for example, Java source files are text files
so is any file created with a “text editor”
Text files are more readable by humans
 Binary files: the bits represent other types of encoded
information, such as executable instructions or numeric data
these files are easily read by the computer but not humans

Java Text Files Java Binary Files


• Source files • Executable files
• Occasionally input (created by compiling
source files)
files
• Usually input files
• Occasionally output
9
files • Usually output files
2.2 Standard: Input, Output and Error Streams

 A Java program opens a file by creating an object and associating a


stream of bytes or characters with it.

 The object’s constructor interacts with the operating system to open the
file.

 Java can also associate streams with different devices. When a Java
program begins executing, in fact, it creates three stream objects that are
associated with devices—System.in, System.out and System.err.

 System.in (the standard input stream object) normally enables a program


to input bytes from the keyboard;

10
 Object System.out (the standard output stream object) normally
enables a program to output character data to the screen; and

 Object System.err (the standard error stream object) normally


enables a program to output character-based error messages to the
screen.

 Each stream can be redirected. For System.in, this capability enables


the program to read bytes from a different source. For System.out
and System.err, it enables the output to be sent to a different location,
such as a computer screen.

 Class System provides methods setIn, setOut and setErr to redirect


the standard input, output and error streams, respectively.

11
 Reading information into a program: A program uses an input stream to
read data from a source, one item at a time.

 Writing information from a program: A program uses an output stream


to write data to a destination, one item at time.

12
Java programs perform file processing by using classes from
2.3 The java.io Package

package java.io

This package includes definitions for stream classes, such as:

FileInputStream (for byte-based input from a file),


FileOutputStream (for byte-based output to a file),
FileReader (for character-based input from a file) and
FileWriter (for character-based output to a file)

Which inherit from classes InputStream, OutputStream, Reader and


Writer, respectively.
FileWriter FileOutputStream

Memory Disk
smiley.txt
smileyOutStream

13 FileWriter smileyOutStream = new FileWriter( new FileOutputStream(“smiley.txt”) );


In addition to the java.io classes, character-based input and
output can be performed with classes Scanner and
Formatter.

Class Scanner is used extensively to input data from the


keyboard—it can also read data from a file.

Class Formatter enables formatted data to be output to


any text-based stream in a manner similar to method
System.out.printf.

(Notice: Write a simple code by using the above classes)


14
3. Class File

 Class File is useful for retrieving information about files or directories


from disk.

 Objects of class File do not open files or provide any file-processing


capabilities.

 However, File objects are used frequently with objects of other java.io
classes to specify files or directories to manipulate.

Creating File Objects:


 Class File provides four constructors.
 The one with a String argument specifies the name of a file or directory
to associate with the File object.
 The name can contain path information as well as a file or directory
name.
15
Two file or directory paths:

An absolute path contains all the directories, starting with the root
directory, that lead to a specific file or directory. (C:/home/index.html)

A relative path normally starts from the directory in which the application
began executing and is therefore “relative” to the current directory.
(index.html or home/index.html)

The constructor with two String arguments specifies an absolute or relative


path as the first argument and the file or directory to associate with the File
object as the second argument.

 The constructor with File and String arguments uses an existing File object
that specifies the parent directory of the file or directory specified by the
String argument.

 The fourth constructor uses a URI object to locate the file. A Uniform
Resource Identifier (URI) is amore general form of the Uniform Resource
Locators (URLs) that are used to locate websites.
16
4. Sequential-Access Text Files
Java imposes no structure on a file. You must structure
files to meet your application’s needs.

To retrieve data sequentially from a file, programs


normally start from the beginning of the file and read
all the data consecutively until the desired information
is found.

Data in many sequential files cannot be modified


without the risk of destroying other data in the file.
Records in a sequential-access file are usually updated
by rewriting the entire file.
17
To retrieve data sequentially from a file, programs start
from the beginning of the file and read all the data
consecutively until the desired information is found.

 It might be necessary to process the file sequentially


several times (from the beginning of the file) during the
execution of a program.

Class Scanner does not allow repositioning to the


beginning of the file. If it’s necessary to read the file
again, the program must close the file and reopen it.

18
5. Object Serialization
Java provides a mechanism called object serialization that
enables entire objects to be written to a file.
A serialized object is represented as a sequence of bytes that
includes the object’s data as well as information about the
object’s type and the types of data it stores.
After a serialized object has been written into a file, it can be
read from the file and deserialized to recreate the object in
memory.
Classes ObjectInputStream and ObjectOutputStream enable
entire objects to be read from or written to a stream.


19Only classes that implement interface Serializable can be
Example 1: Create and Write to a file by using File and
PrintWriter classes
package fileio;

import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;

public class tryfileio {

public static void main(String[] args) {


File file = new File("test.txt");//create test file to which we going to write some thing.
try {
PrintWriter output = new PrintWriter(file); //write some thing to file that refernce to test.txt

output.println("G3Comp");
output.println("A,B & C");
output.close(); //always we need to close opened file
} catch (IOException ex) {
System.out.printf("ERROR:%s\n", ex);
20
}
Example 2: Read from a file by using Scanner class
package fileio;

import java.io.File;
import java.util.Scanner;
import java.io.IOException;

public class tryfileio {

public static void main(String[] args) {


File file = new File("test.txt");//create test file to which we going to write some thing.

try {
Scanner read = new Scanner(file); //Read some thing from test.txt that referenced by file object
String name1=read.nextLine();
String name2=read.nextLine();
read.close(); //always we need to close opened file
System.out.print(name1);
System.out.print(name2);
} catch (IOException ex) {
21
System.out.printf("ERROR:%s\n", ex);
Example 3: Write to a file by using FileWriter class
package fileprocess;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWritingDemo {

public static void main(String[] args) {


File myfile = new File("test1.txt");
try {
FileWriter fwrite = new FileWriter(myfile);
fwrite.write("Hi java learners!!!");
fwrite.flush();
fwrite.close();
} catch (IOException ext) {
System.out.printf("Error : %s", ext);
}
22
}
Notice:

There are different java classes for read and write


operations. It is expected from you to practice creating
file, writing to and reading from the file by applying some
of these classes.

23

You might also like