Tech 5

currygeckoΛογισμικό & κατασκευή λογ/κού

2 Δεκ 2013 (πριν από 3 χρόνια και 8 μήνες)

84 εμφανίσεις

1



Lecture 5




Files and Streams I/O




Antonio Sanchez

Spring 2010

Cocs 20203

Techniques in Programming:

applications in Java

Chapter

19

2

Managing IO

There are various options for the IO of objects:


1. Traditional:

Consider only the data contents of the
variables using


a. Streams



b. Binary Sequences



I. Sequential



II. Random


2. Serialization:

Save the whole object
(i.e. the variables, the
methods and status)

using streams to stored them


For the time being we will discuss the traditional
Streams IO
linked with managing exceptions and stream
tokenization.

We will discuss
Binary Sequences

and
Serialization

later


3

Managing IO



It is through a rich I/O interface that programs are perceived by the
users. Yet for many years the I/O was always the last topic
discussed in a serious programming course


Scientific programmers use Fortran or Algol, yet the business world
needed a language to store files, so then COBOL was created.
Among other things COBOL pay attention to I/O and therefore
became an important element in software development.


We scientific programmers have learned our lesson and today we
consider File I/O processing and important part to software
development. Furthermore the concept of a GUI is getting to be as
important as algorithm development for the use of computers

4

IO, files, memory, registers


and the CPU



Size:
unlimited

Speed:
slow (milisec)

Reliability:
low

Size:
limited

Speed:
high (ns)

Reliability:
high

Cache


memory


Main
Memory

Hard

Disks

CPU

Buffers,

Virtual memory

and Pages

5

Text Files in JAVA 1.4

Use
StreamTokenizer

class

To read from a disk file use
FileReader

and then

StreamTokenizer

classes


Use the
StreamTokenizer

methods to read data
from file
nextToken()
,
nval

and
sval


FileReader stream = new FileReader(fileName);


StreamTokenizer data = new StreamTokenizer(stream);

6

Text Files in JAVA 1.5

Simple use the
Scanner

class

To read from a disk file, use the
FileReader

and
Scanner

classes

Use the
Scanner

methods to read data from
file
next
,
nextLine
,
nextInt
, and
nextDouble

FileReader reader = new FileReader("input.txt");

Scanner in = new Scanner(reader);

7

Writing Text Files

To write to a file, construct a
PrintWriter

object

If file already exists, it is emptied before the
new data are written into it

If file doesn't exist, an empty file is created

PrintWriter out = new PrintWriter("output.txt");

8

Writing Text Files


Use
print

and
println

to write into a
PrintWriter
:





You must close a file when you are done
processing it:



Otherwise, not all of the output may be written
to the disk file

out.println(29.95);

out.println(new Rectangle(5, 10, 15, 25));

out.println("Hello, World!");

out.close();

9

Sample Programs


A collection of file reader is presented
in the folder Application 5


Remember to import the IO classes


import java.io.FileReader;


import java.io.IOException;



import java.io.PrintWriter;


// better just call them all


import java.io*;



import java.util.*;


10

Important File details

Make a good use of


Buffers
// increase I/O speed, remember to flush files


Stream wrappers
// to make your life easier


Tokenizers
// to obtain the components


Dialog boxes
// to handle file names


Collections
// to I/O your data


Arrays of collections
// to structure your data


Exception handlers
// to handle errors


11

Accessing the Humongous JAVA
Classes:

using the API’s

To access the API you can always go to


http://java.sun.com/j2se/1.5.0/docs/api/


Also you can access a more detail API, remember to
select the Open JDK 7 at


http://doc.java.sun.com/DocWeb/


There you have access even to the class code

12

Files and Stream wrappers

and Tokenizers


// input streams


FileInputStream

stream =
new

FileInputStream
(fileName);

InputStreamReader

readerStream =
new InputStreamReader
(stream);

StreamTokenizer data =
new StreamTokenizer
(readerStream);


// output streams



FileOutputStream

stream =
new FileOutputStream
(fileName);

DataOutputStream

writerStream =
new DataOutputStream
(stream);


for
(
int

i = 0; i < myObjects.length ; i = i+ 1)


{ streamString = myObjects[i].name + " " +
myObjects[i].lastName + " " + myObjects[i].idNumber + " " +
myObjects[i].age + " " + myObjects[i].position + " " +
myObjects[i].salary + " " + myObjects[i].sex + "
\
n";


writerStream.writeBytes(streamString);

}

13

Files & Arrays of a Collection

public class ClassObjects


{


String name;


String lastName;


int idNumber;


int age;


String position;


float salary;


String sex;




public ClassObjects () {}


}

ClassObjects[] myObjects;

myObjects[i] = new ClassObjects();

data.nextToken();


myObjects[i].name = data.sval;

data.nextToken();


myObjects[i].lastName = data.sval;

data.nextToken();


myObjects[i].idNumber = (int) data.nval;

data.nextToken();


myObjects[i].age = (int) data.nval;

data.nextToken();


myObjects[i].position = data.sval;

data.nextToken();


myObjects[i].salary = (float) data.nval;

data.nextToken();


myObjects[i].sex = data.sval;


14

Text and Binary Formats


Two ways to store data:


Text format


FileReader / FileWriter


Everything is transformed to Unicode



Binary format
// Note

Do not use extra wrappers


FileInputStream / FileOutputStream


Bytes are used to represent the binary code


15

Text Format


Human
-
readable form


Sequence of characters


Integer 12,345 stored as characters '
1
' '
2
' '
3
' '
4
' '
5
'


Use
Reader

and
Writer

and their subclasses
to process input and output


To read:




To write

FileReader reader = new FileReader("input.txt");

FileWriter writer = new FileWriter("output.txt");

16

Binary Format


Data items are represented in
bytes



Integer 12,345 stored as a sequence of
four bytes
0 0 48 57



Use
InputStream

and
OutputStream

and their subclasses


More compact and more efficient

17

Binary Format


To read:




To write

FileInputStream inputStream


= new FileInputStream("input.bin");

FileOutputStream outputStream


= new FileOutputStream("output.bin");

18

Reading a Single Character
from a File in Text Format


Use
read
method of
Reader

class to
read a single character


returns the next character as an
int



or the integer
-
1

at end of file
// catch Eof exception

Reader reader = . . .;

int next = reader.read();

char c;

if (next !=
-
1)


c = (char) next;

19

Reading a Single Character
from a File in Text Format


Use
read

method of
InputStream

class to read a single byte


returns the next byte as an
int



or the integer
-
1

at end of file

InputStream in = . . .;

int next = in.read();

byte b; if

(next !=
-
1)


b = (byte) next;

20

Text and Binary Format


Use
write

method to write a single
character or byte


read
and
write

are the only input
and output methods provided by the file
input and output classes


Java stream package principle: each
class should have a very focused
responsibility

21

Text and Binary Format


Job of
FileInputStream
: interact
with files and get bytes


To read numbers, strings, or other
objects, combine class with other
classes

22


Input READER Wrappers for text


FileInputStream stream = new FileInputStream(fileName);


InputStreamReader readerStream = new InputStreamReader(stream);


StreamTokenizer data = new StreamTokenizer(readerStream);




or simply




FileReader stream = new FileReader(fileName);


StreamTokenizer data = new StreamTokenizer(stream);




or even using a buffered input




FileReader stream = new FileReader(fileName);


BufferedReader buffStr = new BufferedReader(stream);


StreamTokenizer data = new StreamTokenizer(buffStr);

23


Output WRITER Wrappers for text



FileOutputStream stream = new FileOutputStream(fileName);


DataOutputStream writerStream = new
DataOutputStream(stream);




or simply




FileWriter writerStream = new FileWriter(fileName);




or even using a buffered output




FileWriter stream = new FileWriter(fileName);


BufferedWriter writerStream = new BufferedWriter(stream);

24


Input STREAM Wrapper for binary


( reads bytes, no tokenization )



FileInputStream stream = new FileInputStream(fileName);

Output STREAM Wrapper for binary


( reads bytes, no tokenization )




FileOutputStream stream = new FileOutputStream(fileName);