You are on page 1of 214

POUL KLAUSEN

JAVA 5: FILES AND


JAVA IO
SOFTWARE DEVELOPMENT

2
Java 5: Files and Java IO: Software Development
1st edition
2017 Poul Klausen & bookboon.com
ISBN 978-87-403-1735-0
Peer review by Ove Thomsen, EA Dania

3
JAVA 5: FILES AND JAVA IO Contents

CONTENTS
Foreword 6

1 Introduction 8

2 java.io 10
2.1 Files 10
Exercise 1 16
2.2 Random access files 17
Problem 1 33
2.3 Byte streams 37
Exercise 2 47
Exercise 3 49
Exercise 4 49

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

4
JAVA 5: FILES AND JAVA IO Contents

2.4 Object serialization 50


2.5 Character streams 62
Problem 2 65
2.6 Text scanner 74
Exercise 5 76

3 java.nio 78
3.1 Buffers 79
3.2 Channels 97
3.3 Path and Files 112

4 Operations on simple data types 127


4.1 The integers 127
Exercise 6 131
Exercise 7 135
Problem 3 136
Problem 4 143
Exercise 8 145
Exercise 9 148
Exercise 10 149

5 Final example 150


5.1 The model 153
5.2 The user interface 157
5.3 The dialog box 160

Appendix A 161
The binary number system 162
The hexadecimal system 166
The integers 170
Complement arithmetic 178
Binary operations 189
Encoding of characters 196
Representation of decimal numbers 205

5
JAVA 5: FILES AND JAVA IO Foreword

FOREWORD
This book is the fifth in a series of books on software development. The programming
language is Java, and the language and its syntax and semantic fills obviously much, but
the books have also largely focus on the process and how to develop good and robust
applications. As the previous book, this book has, however, only to a lesser extent focus on
the process, but more on the language and details regarding Java. The subject of this book
are files and what Java provides to IO, and the goal is in details to show how to manipulate
files. Although the files today do not means exactly the same for practical programming, the
processing of files is yet knowledge which is required to have in order to be able to work as
a professional software developer. Finally, it is important to be aware that IO plays a crucial
role in computer networking, and much of what follows will be used and expanded in the
book Java 15 on network programming. Furthermore treat this book data representation,
which are mostly deferred to an appendix, which also gives a brief introduction to the
binary and hexadecimal numbers. The detailed data representation do not play a big role in
everyday life, but also here is a topic that is necessary to have knowledge of, for example,
in the context of computer networks. The book assumes that the reader has a knowledge
corresponding to what is addressed in Java 3 and Java 4, but if you wish, the book can be
postponed until you get the need.

As the title says this series of books deals with software development, and the goal is to
teach the reader how to develop applications in Java. It can be learned by reading about
the subject and by studying complete sample programs, but most importantly by yourself
to do it and write your own programs from scratch. Therefore, an important part of the
books is exercises and problems, where the reader has to write programs that correspond to
the substance being treated in the books. All books in the series is built around the same
skeleton and will consist of text and examples and exercises and problems that are placed
in the text where they naturally belongs. The difference between exercises and problems is
that the exercises largely deals with repetitions of the substance that is presented in the text,
and furthermore it is relatively accurately described what to do. Problems are in turn more
loosely described, and are typically a little bigger and there is rarely any clear best solution.
These are books to be read from start to finish, but the many code examples, including
exercises and problems plays a central role, and it is important that the reader predict in
detail studying the code to the many examples and also solves the exercises and problems
or possibly just studying the recommended solutions.

6
JAVA 5: FILES AND JAVA IO Foreword

All books ends with one or two larger sample programs, which focus primarily is on process
and an explanation of how the program is written. On the other hand appears the code only
to a limited extent if at all and the reader should instead study the finished program
code perhaps while testing the program. In addition to show the development of programs
that are larger than the examples, which otherwise is presented, the aim of the concluding
examples also is to show program examples from varying fields of application.

Most books also ends with an appendix dealing with a subject that would not be treated
in the books. It may be issues on the installation of software or other topics in computer
technology, which are not about software development, but where it is necessary to have
an introductory knowledge. If the reader already is familiar with the subject, the current
appendix can be skipped.

The programming language is, as mentioned Java, and besides the books use the following
products:

-- NetBeans as IDE for application development


-- MySQL to the extent there is a need for a database server (from the book Java 6
onwards)
-- GlassFish as a web server and application server (from the book Java 11 onwards)

It is products that are free of charge and free to install, and there is even talk about products,
where the installation is progressing all by itself and without major efforts and challenges.
In addition, there are on the web detailed installation instructions for all the three products.
The products are available on Windows and Linux, and it therefore plays no special role if
you use Linux or Windows.

All sample programs are developed and tested on machines running Linux. In fact, it plays
no major role, as both Java and other products work in exactly the same way whether the
platform is one or the other. Some places will be in the books where you could see that
the platform is Linux, and this applies primarily commands that concerning the file system.
Otherwise it has no meaning to the reader that the programs are developed on a Linux
machine, and they can immediately also run under Windows unless a program refers to
the file system where it may be necessary to change the name of a file.

Finally a little about what the books are not. It is not how to write or for that matter
reference manuals in Java, but it is as the title says books on software development. It is
my hope that the reader when reading the books and through the many examples can find
inspiration for how to write good programs, but also can be used as a source collection
with a number of examples of solutions to concrete everyday programming problems that
you regularly face as a software developer.

7
JAVA 5: FILES AND JAVA IO Introduction

1 INTRODUCTION
Many applications need to store data persistently and later read them again. As an example
can you think of a word processor, where the user is editing a document. Here, the program
could save the document for later load it again, so you can edit it further. As another
example, one can think of software in a terminal at the supermarket that must be able
to read product prices from a product file as items are scanned, and then the items file is
updated with the items sold and how many. Such data is called persistent, because it is data
that are retained after the program is completed and the machine is turned off.

Applications can store data persistent in several ways, and examples are

-- data can be saved in ordinary flat files


-- objects can be serialized to a file
-- data can be saved in databases
-- data can be saved as XML documents
-- data can be saved as json documents

In this note I only will look at ordinary files, including serialization of objects. In fact, I
already used files several times in the previous books, but the following is a more detailed
review and a description of many of the classes associated with the IO.

Previously, the use of ordinary files to save data, were very common, and although it no
longer has the same interest, there are still many situations where there is a need to store
data in or read data from ordinary files. On the whole, there are many examples where it
is interesting to be able to manipulate the file system from an application, and Java has an
extensive API with classes for the treatment of files. Object serialization is also a matter of
storing data in files, but in such a way that you can save an arbitrary object of any depth
in a file and load the object again. For many simple applications are object serialization
and deserialization interesting, and in addition, serialization is used to send objects through
a network.

A program with many transactions, and it is a program which very often must save data
and read data from an external media will in practice always use a database. A database is
maintained by a software package which include a daemon, that constantly is waiting for
the other applications to enter a request for specific data items or to update the database.
Use of databases from a Java program is the theme for the next book.

8
JAVA 5: FILES AND JAVA IO Introduction

The classes to files are included in the package java.io, but since the package was developed,
Java has expanded with a new package called java.nio primarily for new needs and to
support the facilities in modern operating systems. Both packages are used and will probably
be that for many years to come, so the book covers in following both these two APIs.

The book consists basically of three parts, wherein the first two deals with IO and that the
third part deals with the binary representation of data. If you do not have knowledge of
binary and hexadecimal numbers, it might be a good idea first to read the books appendix.

9
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

2 JAVA.IO
2 JAVA.IO
This
Thischapter
chaptercovers
coversstreams,
streams,which
whichis isa acollection
collectionofofclasses
classesthat
thatprovides
providesthe thebasic
basicinput
input
andand output operations in Java. A stream is a sequence of data that can be sent overa a
output operations in Java. A stream is a sequence of data that can be sent over
communication
communicationchannel channelbetween
betweena source
a sourceandanda destination.
a destination.Both
Boththethesource
sourceand
anddestination
destination
maymay be several things as a program, file, one or another external device such as aprinter,
be several things as a program, file, one or another external device such as a printer,a a
network
networksocket
socketororananarray
arrayininthe
thecomputers
computersmemory.
memory.Java Javaprovides
providesa large
a largenumber
numberofofclasses
classes
available,
available, all of which are intended to encapsulate the many details related to sendingdata
all of which are intended to encapsulate the many details related to sending data
over
over a stream, and it applies to both a stream of bytes, other primitive types and objectsofof
a stream, and it applies to both a stream of bytes, other primitive types and objects
allallkinds.
kinds.This
Thischapter
chaptershows
showsthe theuse
useofofmany
manyofofthe theclasses
classesfrom
from java.io,
java.io,andandthetheclasses
classes
arearepresented primarily through small test methods in the project
presented primarily through small test methods in the project FileProgram. FileProgram.

AsAsmentioned
mentionedabove,
above,the
theconcept
conceptofofa astream
streamhas
hasmany
manyapplications,
applications,but
butthis
thisbook
bookfocus
focus
is isprimarily on streams between a file and a program.
primarily on streams between a file and a program.

2.1 FILES
2.1 FILES
You
Youcan
canthink
thinkofofa afile
fileasasananinfinite
infinitearray
arraywith
withelements
elementsofofthe
thetype
typebyte:
byte:

where
wherea afilefilehas
hasa aso-called
so-calledfile
filepointer
pointerrepresented
representedbybythe thearrow.
arrow.The Thefile
filepointer
pointerindicates
indicates
where the next file operation starts, and the file pointer (the
where the next file operation starts, and the file pointer (the arrow) is moved forward arrow) is moved forward
corresponding
correspondingtotothe thenumber
numberofofbytes bytesread
readororwritten.
written.Files
Filesarearestored
storedononthethemachines
machines
disk,
disk, and the operating system organizes the files in the form of file system that keepstrack
and the operating system organizes the files in the form of file system that keeps track
ofofdirectories and files. Each file has a unique name consisting of the
directories and files. Each file has a unique name consisting of the name of the directory name of the directory
that
thatcontains
containsthe thefile,
file,and
andthe
thefile
filename
namewhich
whichmust mustbebeunique
uniquewithin
withinthe thedirectory.
directory.Java
Javahas
has
a aclass called File, which represents a file by its name and provides
class called File, which represents a file by its name and provides a number of methods a number of methods
available
availablethatthatcancanbebeusedusedtotomanipulate
manipulatethe thefile.
file.

FILE INFO
FILE INFO
The
Thefollowing
followingmethod
methodprints
printsinformation
informationabout
abouta afile:
file:

private static void fileInfo(String filename) throws IOException


{
File file = new File(filename);
System.out.println("Absolute path = " + file.getAbsolutePath());

10
10
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

System.out.println("Canonical path = " + file.getCanonicalPath());


System.out.println("Name = " + file.getName());
System.out.println("Parent = " + file.getParent());
System.out.println("Path = " + file.getPath());
System.out.println("Is absolute = " + file.isAbsolute());
System.out.println(file.exists() ?
"The file object exists" : "The file object is not found");
if (file.exists()) System.out.println(file.isDirectory() ?
"The file object is a folder" : "The file object is a file");
System.out.println(file.length());
System.out.println();
}

The
The method
method has has aa parameter
parameter thatthat isis the
the name
name of of aa file.
file. Note
Note that
that the
the method
method can can raise
raise an
an
IOException,
IOException, and and itit generally
generally occurs,
occurs, ifif you
you try
try to
to perform
perform aa method
method that that works
works on on aa file,
file,
and the method of one reason or another can not be performed.
and the method of one reason or another can not be performed. In this case it is only In this case it is only
one
one of of the
the methods
methods that that can
can raise
raise an an IOException.
IOException. The The method
method creates
creates aa File
File object
object that
that
represents
represents aa file file named
named filename.
filename. You You should
should notenote that
that aa File
File object
object cancan represent
represent both
both aa
directory
directory and and aa file,
file, and
and that
that itit isis not
not aa requirement
requirement that that the
the file
file (or
(or the
the directory)
directory) exists,
exists,
or
or is a legal file name. These conditions have first importance when the object is used. The
is a legal file name. These conditions have first importance when the object is used. The
first
first twotwo statements
statements prints
prints the
the absolute
absolute file file name
name and and thethe canonical
canonical file
file name.
name. InIn most
most cases
cases
itit isis the
the same,
same, butbut the
the canonical
canonical file file name
name isis the
the simplets
simplets possible
possible full
full file
file name
name and and may
may
be
be different
different than
than the
the absolute
absolute file
file name
name (see
(see the
the test
test ofof the
the program).
program).

The
The next
next three
three statements
statements prints
prints respectively
respectively thethe file
file name,
name, the the parent
parent andand the
the path.
path. Here
Here
isis the
the file
file name
name alonealone the
the name
name ofof the
the filen
filen within
within the the directory
directory where
where itit belongs,
belongs, while
while
the
the parent
parent isis the
the file
file name
name of of the
the directory
directory that
that the
the file
file isis aa part
part of.
of. Path
Path isis the
the name
name used
used
to
to create
create the
the File
File object
object and
and hence
hence inin this
this case
case the
the value
value of of the
the parameter
parameter filename.
filename. The
The
last
last three
three statements
statements teststests whether
whether itit isis an
an absolute
absolute file file name,
name, and and whether
whether there
there exists
exists aa
diretory,
diretory, or or aa file
file with
with that
that name.
name. InIn this
this case
case isis tested
tested whether
whether itit isis aa directory
directory or or aa file.
file.
Finally
Finally thethe last
last statements
statements prints
prints the
the file
file size,
size, measured
measured in in bytes.
bytes.

The
The following
following test
test method
method uses
uses the
the method
method fileInfo()
fileInfo() to
to print
print information
information about
about various
various
File
File objects:
objects:

private static void test01()


{
System.out.println("Working Directory = " + System.getProperty("user.dir"));
try
{
fileInfo("/home/pa/doc");
fileInfo("/home/pa/doc/Swing.odt");

11
11
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

fileInfo("/home/pa/doc/xpq/1234");
fileInfo(".");
fileInfo("..");
fileInfo("doc");
}
catch (IOException ex)
{
System.out.println(ex);
}
}

Note especially
Note especially the
the first
first statement
statement that
that prints
prints the
the name
name on
on the
the current
current directory.
directory. You
You are
are
invited
invited to
to test the example
test the example and
and study
study the
the result.
result.

DRIVE
DRIVE INFO
INFO
The
The following
following method
method hashas aa File
File object
object as
as aa parameter,
parameter, and
360
and the
the method
method prints
prints information
information

.
about that disk partition, that contains the
about that disk partition, that contains the file:file:

private static void print(File root)


{
thinking
System.out.println("Partition: " + root);

360
thinking . 360
thinking .
Discover the truth at www.deloitte.ca/careers Dis

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


12
12
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

System.out.println("Free space = " + root.getFreeSpace());


System.out.println("Usable space = " + root.getUsableSpace());
System.out.println("Total space = " + root.getTotalSpace());
System.out.println();
}

All
Allsizes
sizesare
arespecified
specifiedininbytes.
bytes.When
WhengetFreeSpace()
getFreeSpace()andandgetUsableSpace()
getUsableSpace()usually
usuallydodonot
not
show the same value, it is because the latter is a better estimate, since it takes into
show the same value, it is because the latter is a better estimate, since it takes into accountaccount
the
theoverhead
overheadassociated
associatedwith
withthe
thecurrent
currentoperating
operatingsystems
systemsfile
filesystem.
system.TheThemethod
methodisisused
used
ininthe
thefollowing
followingtest
testmethod:
method:

private static void test02()


{
print(new File("/"));
print(new File("/home"));
print(new File("/run/media/pa/HD-PNFU3"));
}

whichfor
which formy
mymachine
machineprints
printsinformation
informationabout
aboutthe
theroot
rootpartition,
partition,the
thepartition
partitionfor
forhome
home
andfor
and foran
anexternal
externalhard
harddrive.
drive.

THESIZE
THE SIZEOF
OFAAFILE
FILEAND
ANDFILTERS
FILTERS

Thefollowing
The followingmethod
methodhas hasasasparameter
parameteraafile
filename
nameand andcreates
createsaacorresponding
correspondingFile Fileobject.
object.
IfIfthis
thisobject
objectrepresents
representsaafile,
file,the
themethod
methodprints
printsthe
thename
nameandandthethesize
sizewhere
wherethethesize
sizeisis
determinedrecursively
determined recursivelyby bythe
themethod
methodgetSize(),
getSize(),which
whichdetermines
determinesthethesize
sizeofofthe
thefile
filetree
tree
havingthe
having theobject
objectfile
fileasasaaroot.
root.Note
Notethat
thatsize
sizeisisaastatic
staticvariable,
variable,which
whichisisdefined
definedatatthe the
startofofthe
start theprogram.
program.

private static void fileSize(String filename, FileFilter filter)


{
File file = new File(filename);
if (file.exists())
{
System.out.println(file.getAbsolutePath());
size = 0;
getSize(file, filter);
System.out.println(size);
}
else System.out.println("Filen findes ikke");
}

13
13
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIOIO java.io
java.Io

The
Themethod
methodhas
hasa aparameter
parameterwhose
whosetype
typeisisFilter.
Filter.ItItisisananinterface
interfacethat
thatdefines
definesa asingle
single
method
method

public boolean accept(File pathname);

The
Themethod
methodshould
shouldtest
testwhether
whethera afile
fileidentified
identifiedbybythe
theparameter
parametermeets
meetscertain
certaincriteria.
criteria.
The
The FileFilter object is tranfered to the method getSize() together with the File objectthat
FileFilter object is tranfered to the method getSize() together with the File object that
isisrepresented
representedbybythe
thefile
filename:
name:

private static void getSize(File file, FileFilter filter)


{
if (file.isDirectory())
{
File[] files = filter == null ? file.listFiles() : file.listFiles(filter);
for (File f : files) getSize(f, filter);
}
else if (filter == null || filter.accept(file)) size += file.length();
}

The
Themethod
methodtests testswhether
whetherthe thefirst
firstargument
argumentisisa adirectory.
directory.IsIsthis
thisthe thecase,
case,thethemethod
method
listFiles()
listFiles() is called, which returns an array of all files in this directory. The method existsinin
is called, which returns an array of all files in this directory. The method exists
several
severaloverloadings
overloadingsand andinclude
includea amethodmethodthat thatasasa aparameter
parameterhas hasa afilter
filterand
andreturns
returnsonly
only
the
thefiles
filesthat
thatmeet
meetthe thefilter.
filter.With
Withthe thearray
array(as(aspossibly
possiblycan canbebeempty)
empty)available
availablethe themethod
method
getSize()
getSize()isiscalled
calledrecursively
recursivelyfor forallallfiles
filesininthe
thearray.
array.IfIfthe
themethod
methodisiscalledcalledandandthe
thefirst
first
parameter is not a directory, there is nothing else than the static
parameter is not a directory, there is nothing else than the static variable size is counted variable size is counted
with
withthethefiles
filessize
sizeififititisisa afile
filetotobebeincluded
includedaccording
accordinga apossibly
possiblyfilter.
filter.

Below
Belowisisa atest
testmethod
methodthat thatdetermines
determinesthe thesize
sizeofofallallfiles
filespartly
partlyunder
underthe
thecurrent
currentdirectory
directory
and
and partly under the users home directory. In both cases, it happens with and withouta a
partly under the users home directory. In both cases, it happens with and without
filter,
filter,where
wherethethefilter
filteraccepts
acceptsfiles
filesthat
thatare
areeither
eithera adirectory
directoryorora aregular
regularfile
filewhose
whosename
name
ends
endswith
with.java:
.java:

private static void test03()


{
FileFilter filter = new FileFilter() { public boolean accept(File f) {
return f.isDirectory() || (f.isFile() && f.getName().endsWith(".java")); } };
fileSize(".", null);
fileSize(".", filter);
fileSize(System.getProperty("user.home"), null);
fileSize(System.getProperty("user.home"), filter);
}

You
Youmust
mustnote
notehow
howthe
thefilter
filterisisdefined
definedon
onthe
thebasis
basisofofanananonymous
anonymousclass.
class.

1414
JAVA 5: FILES AND JAVA IO java.Io
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.Io
java.io

MANIPULATION OF THE FILE SYSTEM


MANIPULATION OF THE FILE SYSTEM
The class file also has a variety of methods that can manipulate the file system, for example
The
The class file also has a variety of methods that can manipulate the file system, for example
create directories and files and delete them again. There are many (and you are encouraged
create directories and files and delete them again. There are many (and you are encouraged
to examine which), and the following test method shows the use of a few of them, but
to examine which), and the following test method shows the use of a few of them, but
first a little helper method:
first a little helper method:

private static void showFiles(File file)


private static void showFiles(File file)
{
{
System.out.printf(file.isDirectory() ? "[%s]\n" : "%s\n", file.getName());
System.out.printf(file.isDirectory() ? "[%s]\n" : "%s\n", file.getName());
if (file.isDirectory())
if (file.isDirectory())
{
{
File[] files = file.listFiles();
File[] files = file.listFiles();
for (File f : files) showFiles(f);
for (File f : files) showFiles(f);
}
}
}
}

The method prints recursive a file tree with a particular File object as root. The test method
The
The method prints recursive a file tree with a particular File object as root. The test method
is presented below:
is presented below:

private static void test04()


private static void test04()
{
{

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

15
15
15
JAVA 5: FILES AND JAVA IO java.io
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.Io
java.Io

File
File file
file =
= new
new File(System.getProperty("user.home")
File(System.getProperty("user.home") +
+ "/test");
"/test");
try
try
{
{
file.mkdir();
file.mkdir();
(new
(new File(file,
File(file, "filer")).mkdir();
"filer")).mkdir();
(new
(new File(file,
File(file, "filer/file1")).createNewFile();
"filer/file1")).createNewFile();
(new File(file, "filer/file2")).createNewFile();
(new File(file, "filer/file2")).createNewFile();
showFiles(file);
showFiles(file);
file.deleteOnExit();
file.deleteOnExit();
}
}
catch
catch (Exception
(Exception ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

The
The first
first statement
statement defines
defines aa File
File object
object that
that references
references aa file
file named
named test
test in
in the
the users
users home
home
directory. Next, is created a directory with this name and including a sub-directory
directory. Next, is created a directory with this name and including a sub-directory named named
files.
files. Below
Below again
again are
are created
created two
two ordinary
ordinary files,
files, then
then the
the method
method showFiles()
showFiles() is
is called.
called. The
The
result
result isis the
the following:
following:

[test]
[test]
[filer]
[filer]
file2
file2
file1
file1

The last statement in the test method performs deleteOnExit(), which deletes all files and
The
directories as this File object has created. The method has probably not a great practical
use, but it is smart for testing to clean up as in this example.

EXERCISE 1
You must write a command, you can call Seek. The command shoul be performed in the
following manner

java
java -jar
-jar Seek.jar
Seek.jar directory
directory [text]
[text]

where directory
where directory is
is the
the name
name of
of aa directory,
directory, while
while text
text is
is aa search
search text.
text. The
The command
command should
should
print the absolute file names of all files in the file tree whose root is directory and the file
name contains
name contains the
the search
search text
text text.
text. The
The result
result could
could be
be the
the following:
following:

16
16
16
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.io
java.Io

where
wherefor foreach
eachfile
fileare
areshown
shownthethefile
filename,
name,the thedate
datewhen
whenthe
thefile
filewas
waslast
lastmodified
modifiedand
and
the
thefile
filesize.
size.The
Theprogram
programmust mustnotnotdisplay
displaythe
thenames
namesofofdirectories
directoriesthat
thatmatch
matchthe
thesearch
search
criteria,
criteria,and
andififthe
thesearch
searchcriterion
criterionisisempty
empty(the (thelast
lastparameter
parameterisismissing),
missing),the
thecommand
command
should
shoulddisplay
displayall
allfiles
filesininthe
thecurrent
currentfile
filetree.
tree.

IfIfthe
thefirst
firstparameter
parameterisisnot
notthe
thename
nameofofan
anexisting
existingdirectory,
directory,the
thecommand
commandmust
mustsimply
simply
print
printananerror
errormessage
messageon onthe
thescreen.
screen.

2.2
2.2 RANDOM
RANDOMACCESS
ACCESSFILES
FILES
Above
AboveI Idescribed
describedthe theclass
classFile,
File,and
andhowhowaaFileFileobject
objectcan
canbebeused
usedtotoget
getinformation
informationaboutabout
files
filesand
anddirectories
directoriesandandtotomanipulate
manipulatethe thefile
filesystem.
system.InInthetherest
restofofthis
thischapter,
chapter,I Iwill
will
show
showhowhowtotooperate
operateon onthetheindividual
individualfilesfilesand
andthus
thusprimarily
primarilyhowhowtotowrite
writedata
datatotofiles
files
and
andread
readthe
thecontent
contentofoffiles.
files.Ill
Illstart
startwith
withRandomAccessFiles,
RandomAccessFiles,which whicharearefiles
fileswhere
whereyou you
can
canboth
bothread
readand
andwrite
writedata
dataand andthusthusfiles
filesthat
thatprograms
programscan canasasuse
useasassimple
simpledatabases.
databases.
InInfact,
fact,that
thatkind
kindofoffiles
fileshas
hasnot
notsosomuchmuchinterest
interesttoday,
today,butbutthey
theyare
aregood
goodtotoknow,
know,and and
totoknow
knowhow howaaprogram
programwrites
writestotoand andreads
readsfromfromfiles,
files,and
andthat
thatisiswhy
whyI Iwill
willstart
startwith
with
random
randomaccess
accessfiles.
files.They
Theyare areininJava
Javarepresented
representedby bythetheclass
classRandomAccessFile.
RandomAccessFile.Consider
Consider
the
thefollowing
followingtest
testmethod:
method:

private static void test05()


{
int t1 = 0x41424344;
int t2 = 0x45464748;
int t3 = 0x494a4b4c;
int t4 = 0x4d4e4f50;
int t5 = 0x51525354;
System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
System.out.println(t4);

1717
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

System.out.println(t5);
RandomAccessFile dataFile = null;
try
{
dataFile = new RandomAccessFile("numbers.dat", "rw");
dataFile.writeInt(t1);
dataFile.writeInt(t2);
dataFile.writeInt(t3);
dataFile.writeInt(t4);
}
catch (IOException ex)
{
System.out.println(ex);
}
finally
{
if (dataFile != null) try { dataFile.close(); } catch (IOException e) {}
}
try (RandomAccessFile file = new RandomAccessFile("numbers.dat", "r"))
{
int sum = file.readInt();
sum += file.readInt();
sum += file.readInt();
sum += file.readInt();

e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili www.discovermitas.com
Maersk.com/Mitas e G
I joined MITAS because for Engine
I wanted real responsibili Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
ree wo
work
or placements ssolve pr

18
18
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

System.out.println(t1 + t2 + t3 + t4);
System.out.println(sum);
}
catch (IOException ex)
{
System.out.println(ex);
}
try (RandomAccessFile file = new RandomAccessFile("numbers.dat", "rw"))
{
file.seek(8);
file.writeInt(t5);
}
catch (IOException ex)
{
System.out.println(ex);
}
try (RandomAccessFile file = new RandomAccessFile("numbers.dat", "r"))
{
long sum = file.readInt();
sum += file.readInt();
sum += file.readInt();
sum += file.readInt();
System.out.println((long)t1 + t2 + t5 + t4);
System.out.println(sum);
}
catch (IOException ex)
{
System.out.println(ex);
}
try (RandomAccessFile file = new RandomAccessFile("numbers.dat", "r"))
{
byte[] arr = new byte[16];
file.read(arr);
String str = new String(arr);
System.out.println(str);
}
catch (IOException ex)
{
System.out.println(ex);
}
try (RandomAccessFile file = new RandomAccessFile("numbers.dat", "r"))
{
double x1 = file.readDouble();
double x2 = file.readDouble();
System.out.println(x1);
System.out.println(x2);
}

19
19
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io
JAVA 5: FILES AND JAVA IO java.Io

catch (IOException ex)


catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

The
The first
first thing
thing that
that happens
happens isis the
the creation
creation of
of 55 int
int variables
variables that
that are
are written
written on
on the
the screen:
screen:
The first thing that happens is the creation of 5 int variables that are written on the screen:

1094861636
1094861636
1162233672
1162233672
1229605708
1229605708
1296977744
1296977744
1364349780
1364349780

The numbers
The numbers are notnot so interesting,
interesting, but youyou should note
note how they
they are initialized
initialized as
The numbers areare not soso interesting, but
but you should
should note how
how they are
are initialized asas
hexadecimal
hexadecimal values consisting of 4 bytes. If you do not know hexadecimal numbers, you
hexadecimal values
values consisting
consisting of
of 44 bytes.
bytes. If
If you
you do
do not
not know
know hexadecimal
hexadecimal numbers,
numbers, you you
can
can read the appendix to this book.
can read
read the
the appendix
appendix toto this
this book.
book.

To be
To be able to to write to
to a file, itit must
must first be
be opened and
and must then
then be closed
closed again. In
In
To be able
able to write
write to aa file,
file, it must first
first be opened
opened and must
must then be be closed again.
again. In
this case
this case is defined aa variable
variable dataFile ofof the type
type RandomAccessFile. It
It is opened in in the try
try
this case isis defined
defined a variable dataFile
dataFile of the
the type RandomAccessFile.
RandomAccessFile. It isis opened
opened in the
the try
block with
block with the statement
statement
block with the the statement
dataFile = new RandomAccessFile("numbers.dat", "rw");
dataFile = new RandomAccessFile("numbers.dat", "rw");

The statement creates a file under the current directory with the name numbers.dat, while
The statement
The statement creates
creates aa file
file under
under thethe current
current directory
directory with with the
the name
name numbers.dat,
numbers.dat, whilewhile
the last parameter tells how to open the file. Basically, there are two options r and rw (there
the last
the last parameter
parameter tells
tells how
how toto open
open the
the file.
file. Basically,
Basically, there
there are are two
two options
options rr and
and rw rw (there
(there
are actually two other options). Here rw means you can both read and write to the file,
are actually
are actually two
two other
other options).
options). Here
Here rw rw means
means you you can can bothboth read
read and
and write
write to to the
the file,
file,
while r means that you can only read the file. The above statement thus opens the file for
while rr means
while means that
that you
you can
can only
only read
read the
the file.
file. The
The above
above statement
statement thusthus opens
opens the the file
file for
for
both reading and writing. If the file does not exist, it is created, but otherwise it is just
both reading
both reading and
and writing.
writing. IfIf the
the file
file does
does not
not exist,
exist, itit isis created,
created, but
but otherwise
otherwise itit isis just
just
opened and the file pointer is placed at the beginning of the file, so the next file operation
opened and
opened and the
the file
file pointer
pointer isis placed
placed atat the
the beginning
beginning of of thethe file,
file, so
so the
the next
next file
file operation
operation
is carried out from this place.
isis carried
carried out
out from
from this
this place.
place.

After the file is opened, the first 4 of the above numbers are written to the file. The class
After the
After the file
file isis opened,
opened, the
the first
first 44 of
of the
the above
above numbers
numbers are are written
written toto the
the file.
file. The
The class
class
RandomAccessFile has a method writeInt(), which writes an integer to the file. Exactly what
RandomAccessFile has
RandomAccessFile has aa method
method writeInt(),
writeInt(), which
which writes
writes anan integer
integer to
to the
the file.
file. Exactly
Exactly whatwhat
happens is that the method writes 4 bytes from the location where the file pointer is, and
happens isis that
happens that thethe method
method writes
writes 44 bytes
bytes from
from thethe location
location where
where thethe file
file pointer
pointer is,
is, and
and
after the method is performed, the file pointer is moved 4 bytes forward. The result is that
after the
after the method
method isis performed,
performed, the the file
file pointer
pointer isis moved
moved 44 bytes
bytes forward.
forward. The The result
result isis that
that
the four writeInt() statements writes 16 bytes to the file, which represents the 4 integers.
the four
the four writeInt()
writeInt() statements
statements writes
writes 16 16 bytes
bytes to
to the
the file,
file, which
which represents
represents thethe 44 integers.
integers.

20
20
20
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io

After
After the the four
four statements
statements isis performed,
performed, thethe file
file isis closed.
closed. It
It isis important,
important, as as the
the writeInt()
writeInt()
statements
statements writes
writes toto aa memory
memory buffer.
buffer. The
The content
content of of this
this buffer
buffer isis first
first written
written physical
physical toto
the file when the buffer is full or the file is closed. Another reason for the
the file when the buffer is full or the file is closed. Another reason for the file to be closed file to be closed
isis that
that you
you thereby
thereby releases
releases the
the resources
resources allocated
allocated to to the
the file.
file. Closing
Closing aa file
file with
with the
the close()
close()
isis important
important andand toto ensure
ensure that
that the
the statement
statement isis executed,
executed, itit isis placed
placed inin aa finally
finally block
block that
that
isis performed
performed regardless
regardless ofof whether
whether anan exception
exception occurs
occurs or
or not.
not.

The
The above
above actually
actually defines
defines aa pattern
pattern for
for how
how to
to treat
treat files:
files:

1.
1. open
open the
the file
file
2.
2. performs the wanted
performs the wanted file
file operations
operations
3. close the filen
3. close the filen

After
After having
having written
written four
four numbers
numbers to
to the
the file,
file, itit isis opened
opened again
again to
to read
read the
the contents:
contents:

try (RandomAccessFile file = new RandomAccessFile("tal.dat", "r"))

21
21
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io

This
This time
time the the file
file isis opened
opened in in aa statement
statement afterafter the
the try.
try. ItIt isis aa syntax
syntax that
that isis really
really just
just
aa short
short way
way of of writing
writing the the above,
above, but
but itit guarantees
guarantees that
that the
the filefile will
will be
be closed
closed when
when the the
program exits the try block. The syntax is in most cases preferable, first,
program exits the try block. The syntax is in most cases preferable, first, it is actually shorter it is actually shorter
and
and more
more readable,
readable, and and secondly
secondly youyou are
are sure
sure that
that you
you remember
remember to to close
close the
the file.
file. After
After
the
the file
file isis opened,
opened, itit performs
performs aa readInt()
readInt() operation
operation four
four times
times that that reads
reads four
four integers
integers inin
the
the file,
file, and
and the
the sum
sum of of these
these numbers
numbers isis determined
determined and and printed
printed alongalong with
with thethe sum
sum ofof
the four numbers that are written in the file. The idea is that you
the four numbers that are written in the file. The idea is that you have to see that you get have to see that you get
the
the same
same result:
result:

4783678760
4783678760

and
and thus
thus itit isis the
the same
same four
four numbers
numbers that that are
are read
read as
as thethe four
four numbers
numbers originally
originally written
written in
in
the
the file.
file. You
You should
should note
note that
that the
the method
method readInt()
readInt() reads
reads 44 bytes
bytes from
from the
the location
location where
where
the
the file
file pointer
pointer isis and and converts
converts these
these 44 bytes
bytes toto an
an int.
int. After
After the
the method
method isis performed,
performed, the the
file
file pointer
pointer isis movedmoved 44 bytes
bytes forward.
forward. The The method
method interprets
interprets therefore
therefore notnot what
what the
the 44 bytes
bytes
contains,
contains, and and wherewhere the
the result
result isis aa sense
sense integer.
integer. 44 bytes
bytes can
can be
be interpreted
interpreted as as an
an integer,
integer,
no
no matter
matter whatwhat theythey contains.
contains. As
As aa next
next step
step the
the file
file isis opened
opened again
again for
for reading
reading and
and writing:
writing:

try (RandomAccessFile file = new RandomAccessFile("tal.dat", "rw"))


{
file.seek(8);
file.writeInt(t5);
}

Then
Then the
the file
file pointer
pointer isis moved
moved 88 bytes
bytes forward,
forward, which
which means
means that
that itit points
points at
at the
the start
start of
of
the
the third
third number
number in in the
the file.
file. The
The method
method then
then writes
writes another
another number
number to to the
the file,
file, which
which
means
means that the third number is overwritten, and the value is now the value of t5. After
that the third number is overwritten, and the value is now the value of t5. After
these
these statements are executed, the file is opened again for reading, and the sum of the
statements are executed, the file is opened again for reading, and the sum of the
four
four numbers
numbers determined
determined again,
again, and
and you
you will
will find
find that
that you
you get
get aa different
different result,
result, but
but the
the
correct
correct result:
result:

4918422832
4918422832

In aa RandomAccessFile
In RandomAccessFile you
you can
can thus
thus use
use the
the method
method seek()
seek() to
to move
move the
the file
file pointer
pointer to
to aa
random position
random position and
and read
read or
or write
write from
from that
that position.
position.

22
22
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.io
java.Io

The
Thefile
fileisisopened
openedfor
forreading
readingagain:
again:

try (RandomAccessFile file = new RandomAccessFile("tal.dat", "r"))


{
byte[] arr = new byte[16];
file.read(arr);
String str = new String(arr);
System.out.println(str);
}

and
andthethecode
codecreates
createsan anarray
arraywith
withroom
roomfor for16
16bytes
bytes(that
(thatexactly
exactlymatches
matchesthe thecontents
contents
ofofthe
thefile
fileififyou
youexamine
examineits itsproperties
propertieswith
withFiles
Filesyou
youcancansee
seethat
thatitittakes
takesupup1616bytes).
bytes).
Next,
Next,read
readthethefile
filewith
withthethemethod
methodread()
read()and
andthe
thearray
arrayasasaaparameter.
parameter.ThisThismethod
methodreads
reads
aamaximum
maximum of 16 bytes in the file (less if there are not 16 bytes after the file pointer).The
of 16 bytes in the file (less if there are not 16 bytes after the file pointer). The
16 bytes are used to initialize a string, and the
16 bytes are used to initialize a string, and the result is: result is:

ABCDEFGHQRSTMNOP

The
Thegoal
goalisistotoshow
showthat
thateven
eventhough
thoughthethefile
filecontains
containsfour
fourintegers
integerswhich
whichtotal
totaltakes
takesup up16
16
bytes,
bytes,ititcan
canbe beinterpreted
interpretedasasanything,
anything,and
andititisisthe
theprogram
programthatthatreads
readsthe
thefiles
filescontents
contents
that
that determines how the results should be interpreted. It is further illustrated withthe
determines how the results should be interpreted. It is further illustrated with thelast
last
statements in the test method that reads the contents of the file and interprets
statements in the test method that reads the contents of the file and interprets it as two it as two
numbers
numbersofofthe thetype
typedouble.
double.

HISTORY
HISTORYAGAIN
AGAIN
InInthe
thelast
lastexample
exampleininthe thethe
thebook
bookJava
Java22I Ishowed
showedaaprogram
programwhere
whereyou youcould
couldenter
enter
information
information about historic people and save the information by object serialization. Iwill
about historic people and save the information by object serialization. I will
show a different version of the program where the difference is that the persons
show a different version of the program where the difference is that the persons instead are instead are
stored
storedininaaRandomAccessFile.
RandomAccessFile.Let Letme
mesay
sayimmediately
immediatelythat thatthis
thissolution
solutionhashasnonoadvantages,
advantages,
and
andthe
thegoal
goalisisonly
onlytotoshow
showan anexample
exampleofofaafile
filecontaining
containingrecords
recordsofoffixed
fixedlength,
length,formerly
formerly
aatypical application of files.
typical application of files.

The
Thestarting
startingpoint
pointwas
wasthe
thefollowing
followingclass,
class,which
whichrepresents
representsaahistoric
historicperson
person(where
(whereI Ihave
have
not
notshown
shownthetheget
getand
andset
setmethods):
methods):

public class Person implements Comparable<Person>, Serializable


{
private int recnr = -1; // idenfification of a person
private String name; // the person's name
private String job; // the person's position
private String text; // a description
private int from; // birth, start of reign or otherwise
private int to; // year of when the person is dead

2323
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

public Person(String name, String job, String text, int from, int to)
{
this.name = name;
this.job = job;
this.text = text;
this.from = from;
this.to = to;
}

public Person(int recnr, String navn, String job, String tekst, int fra, int til)
{
this(navn, job, tekst, fra, til);
this.recnr = recnr;
}

Compared
Comparedtotothetheprevious
previousversion
versionofofthetheprogram
programI have
I havemade
madea single
a singlechange,
change,since sincethethe
class
classis isextended
extendedwithwithananintintvariable
variablenamed
namedrecnr.
recnr.There
Therearearealso
alsodefined
definedboth
bothgetgetand andsetset
methods
methodsforforthat thatvariable,
variable,andandthat
thatshould
shouldcontain
containa persons
a personslocation
locationininthethefile.
file.Finally
Finallyis is
added
added anan extra constructor.
extra constructor. TheTheclass is is
class defined Serializable,
defined and
Serializable, and as as
Person
Personobjects
objects nono longer
longer
should
shouldbebeserialized,
serialized,it itcould
couldbebedeleted.
deleted.

BUSINESS HAPPENS HERE.


www.fuqua.duke.edu/globalmba

24
24
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io

The
The file
file must
must contain
contain objects
objects ofof the
the type
type Person,
Person, butbut to
to be
be able
able to
to read
read these
these objects
objects again
again
(place
(place the
the file
file pointer
pointer where
where aa person
person starts),
starts), they
they must
must have
have aa fixed
fixed size.
size. Because
Because the
the first
first
three
three of
of the
the variables
variables are
are strings,
strings, they
they do do not
not have
have aa fixed
fixed length.
length. Therefore,
Therefore, itit is
is necessary
necessary to
to
select
select aa maximum
maximum length
length of
of each
each ofof these
these values.
values. AsAs you
you will
will see
see in
in the
the next
next book,
book, the
the same
same
is
is necessary
necessary ifif Person
Person objects
objects should
should be be stored
stored inin aa database,
database, so
so in
in fact
fact the
the limitation
limitation isis quite
quite
usual.
usual. The
The following
following class
class defines
defines aa file
file (a
(a database)
database) toto Person
Person objects
objects oror individual
individual records:
records:

package history;

import java.io.*;
import palib.util.*;
public class PersonDB
{
public static final int NLENGTH = 50;
public static final int JLENGTH = 30;
public static final int TLENGTH = 500;

private static final int RLENGTH = 2 * (NLENGTH + JLENGTH + TLENGTH) + 12;


private RandomAccessFile file = null;

public PersonDB(String path) throws IOException


{
file = new RandomAccessFile(path, "rw");
}

public void append(Person pers) throws IOException


{
pers.setRecnr(length());
file.seek(file.length());
write(pers);
}

public int length() throws IOException


{
return (int) file.length() / RLENGTH;
}

public Person select(int recnr) throws IOException


{
if (recnr < 0 || recnr >= length())
throw new IOException("Illegal recordnumber");
file.seek(recnr * RLENGTH);
return read();
}

25
25
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

public void update(Person pers) throws IOException


{
if (pers.getRecnr() < 0 || pers.getRecnr() >= length())
throw new IOException("Illegal record number");
file.seek(pers.getRecnr() * RLENGTH);
int rec = file.readInt();
if (rec != pers.getRecnr()) throw new IOException("Illegal recordnumber");
file.seek(pers.getRecnr() * RLENGTH);
write(pers);
}

public void delete(Person pers) throws IOException


{
if (pers.getRecnr() < 0 || pers.getRecnr() >= length())
throw new IOException("Illegal recordnumber");
file.seek(pers.getRecnr() * RLENGTH);
file.writeInt(-1);
}

public void close()


{
try
{
if (file != null) file.close();
}
catch (IOException ioe)
{
}
file = null;
}

private void write(Person pers) throws IOException


{
file.writeInt(pers.getRecnr());
file.writeChars(Str.left(Str.cut(pers.getName(), NLENGTH), NLENGTH, ));
file.writeChars(Str.left(Str.cut(pers.getJob(), JLENGTH), JLENGTH, ));
file.writeChars(Str.left(Str.cut(pers.getText(), TLENGTH), TLENGTH, ));
file.writeInt(pers.getFrom());
file.writeInt(pers.getTo());
}

private Person read() throws IOException


{
int rec = file.readInt();
if (rec == -1) return null;
String navn = read(NLENGTH);

26
26
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

String job = read(JLENGTH);


String tekst = read(TLENGTH);
int fra = file.readInt();
int til = file.readInt();
return new Person(rec, navn, job, tekst, fra, til);
}

private String read(int length) throws IOException


{
StringBuilder buff = new StringBuilder();
for (int i = 0; i < length; ++i) buff.append(file.readChar());
return buff.toString().trim();
}
}

Excellent Economics and Business programmes at:

The perfect start


of a successful,
international career.

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

27
27
JAVA 5: FILES AND JAVA IO java.io

The class starts with defining some constants that specifies that the name has of maximum
of 50 characters, that the position has a maximum 30 characters, and the description a
maximum of 500 characters. Finally is define a constant that indicates the size of a record.
The sum of these three constants are multiplied by 2, because a character (a char) occupies 2
bytes. The last number 12 is the size of three integers. This means that a Person record always
occupies 1172 bytes in the file. You should note that in most cases it will be considerably
more than necessary and that the file will thus contain some wasted space, but these are
the conditions for a file of this type. This is the price that you must pay to be able to read
a record stored at a specific location.

The class has an instance variable of the type RandomAccessFile and the constructor opens
the file for read and write. Note that the constructor raises an exception if the file can not
be opened. The class offers the following services:

-- length(), that returns the number of records in the file


-- select(), that returns the record with a certain record number
-- append(), that adds a new record to the file
-- update(), that modify the content of a certain record
-- delete(), that delete a certain record
-- close(), that closes the file

The implementation of these methods is generally without problems, but delete() is an


exception. The question is what should happens when you delete a record, as you logically
get a hole in the file. In practice, there are several solutions. For example you could
move the last record to the place where the deleted record was and then reduce the length
of the file with the size of a record. The main problem with this strategy is, that a record
in this way must change the record number, and the number then can not be used to
identify a certaing record the record number can not be the key. In this case, I will use a
strategy where the record number set to -1, thus indicating that the record is deleted. The
disadvantage of this approach is that the file that will contain a number of dead records,
and you should therefore test whether a record is deleted when you reads in the file. Has
deleted many records, it may also mean that the file size is unnecessarily large. The problem
can be solved by reusing deleted records when adding new records (it is not done in this
case). You must specifically noting, how the method delete() are implemented, and how to
delete a record by writing the number -1 to the file. When the record number is the first
field, it corresponds exactly to write the number -1 to the file.

28
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io

The
The method
method append()
append() have
have asas aa parameter,
parameter, the the Person
Person object
object toto be
be added
added to to the
the file.
file. The
The
method
method starts
starts byby allocating
allocating the
the objects
objects record
record number
number as as the
the next
next record
record in in thethe file,
file,
and
and then
then set
set the
the file
file pointer
pointer toto the
the end
end of of the
the file.
file. The
The object
object isis then
then written
written toto thethe file
file
with
with the
the method
method write().
write(). Here
Here you you must
must noticenotice how
how to to save
save aa String
String that
that happens
happens with with
writeChars().
writeChars(). First
First are
are used
used two
two methods
methods from from PaLib
PaLib that
that ensures
ensures that
that the
the string
string isis not
not too
too
long,
long, and
and in
in the
the case
case where
where the
the String
String isis shorter
shorter than
than maximum,
maximum, itit isis filled
filled with
with blanks
blanks toto
the
the maximum
maximum width.width.

The
The method
method update()
update() works works inin principle
principle inin the
the same
same way, way, only
only isis used
used the
the Person
Person objects
objects
record
record number
number to to position
position the
the file
file pointer
pointer in
in the
the right
right place.place. The
The method
method first
first reads
reads an
an int
int to
to
test
test whether
whether itit isis the
the right
right record
record number,
number, andand ifif itit isis the
the case,
case, writes
writes the
the updates
updates to to the
the file.
file.

The
The previous
previous version
version ofof the
the program
program has has aa class
class called
called Persons,
Persons, and
and itit isis rewritten
rewritten asas shown
shown
below,
below, because
because the
the program
program instead
instead of of store
store Person
Person objects
objects byby serilalization
serilalization usesuses an
an object
object
of
of type
type PersonDB.
PersonDB. TheThe class
class isis expanded
expanded with with aa new
new instance
instance variable
variable called
called path,
path, which
which
isis initialized
initialized byby the
the constructor
constructor and and contains
contains the the file
file name,
name, butbut otherwise
otherwise the the class
class works
works
in
in principle
principle inin the
the same
same way
way as as inin the
the first
first version
version of of the
the program.
program. The The various
various methods
methods
are
are of of course
course changed,
changed, butbut the
the difference
difference isis only
only that
that they
they store
store the
the objects
objects inin aa different
different
way.
way. IveIve shown
shown thethe whole
whole class
class below,
below, and and you
you should
should study
study the
the code
code and and how
how thethe class
class
PersonDB
PersonDB isis used:
used:

package history;

import java.util.*;
import java.io.*;

public class Persons implements Iterable<Person>


{
private static String path;
private ArrayList<Person> list;

public Persons(String path) throws IOException


{
this.path = path;
load();
}

public Iterator<Person> iterator()


{
return list.iterator();
}

29
29
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

public boolean add(Person pers)


{
PersonDB db = null;
try
{
db = new PersonDB(path);
db.append(pers);
list.add(pers);
return true;
}
catch (IOException ex)
{
return false;
}
finally
{
if (db != null) db.close();
}
}

30
30
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

public boolean remove(Person pers)


{
PersonDB db = null;
try
{
db = new PersonDB(path);
db.delete(pers);
return list.remove(pers);
}
catch (IOException ex)
{
return false;
}
finally
{
if (db != null) db.close();
}
}

public boolean update(Person pers)


{
PersonDB db = null;
try
{
db = new PersonDB(path);
db.update(pers);
return true;
}
catch (IOException ex)
{
return false;
}
finally
{
if (db != null) db.close();
}
}

private void initialize()


{
list = new ArrayList();
for (int i = 0;i < navne.length; ++i)
{
String job = navne[i][0].equals("Margrete d. 1.") ||
navne[i][0].equals("Margrethe d. 2.") ? "Queen" : "King";
int fra = navne[i][1].length() > 0 ? Integer.parseInt(navne[i][1]) : -9999;
int til = navne[i][2].length() > 0 ? Integer.parseInt(navne[i][2]) : 9999;
list.add(new Person(navne[i][0], job, "", fra, til));

31
31
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

}
store();
}

private void load() throws IOException


{
File file = new File(path);
if (file.exists() && file.isFile())
{
PersonDB db = null;
try
{
list = new ArrayList();
db = new PersonDB(path);
for (int rec = 0; rec < db.length(); ++rec)
{
Person pers = db.select(rec);
if (pers != null) list.add(pers);
}
}
finally
{
if (db != null) db.close();
}
}
else initialize();
Collections.sort(list);
}

private void store()


{
PersonDB db = null;
try
{
db = new PersonDB(path);
for (Person pers : list) db.append(pers);
}
catch (Exception ex)
{
System.out.println(ex);
}
finally
{
if (db != null) db.close();
}
}

32
32
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io
JAVA 5: FILES AND JAVA IO java.Io

private static
static String[][]
String[][] navne
navne == {{
private
{{ "Gorm
"Gorm den
den Gamle",
Gamle", "",
"", "958"
"958" },
},
{ "Harald Bltand", "958", "986" },
{ "Harald Bltand", "958", "986" },

};
};
}}

Then there
Then
Then there are
there are the
are the classes
the classes for
classes for the
for the user
the user interface,
user interface, which
interface, which III have
which have not
have not shown,
not shown, and
shown, and they
and they are
they are
are
basically not
basically
basically not changed
not changed compared
changed compared to
compared to the
to the first
the first version
first version of
version of the
of the program.
the program.
program.

PROBLEM
PROBLEM 1
1
You must
You
You must in
must in this
in this problem
this problem write
problem write aaa program
write program similar
program similar to
similar to the
to the program
the program above,
program above, but
above, but the
but the program
the program
program
must instead
must
must instead maintain
instead maintain aaa product
maintain product database.
product database. A
database. A product
A product is
product is described
is described with
described with four
with four fields:
four fields:
fields:

public class
class Product
Product
public
{
{
private int pnr; // product number
private int pnr; // product number
private String name; // product name
private String name; // product name
private short units; // units in stock
private short units; // units in stock
private float price; // unit price
private float price; // unit price

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

enroll by September 30th, 2014 and


save up to 16% on the tuition!
pay in 10 installments / 2 years
Interactive Online education
visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

33
33
33
JAVA 5: FILES AND JAVA IO java.io
java.Io

The
The product number is a sequential number starting with 0 (the first product should have
product number 0), and each time a new product is created, it is assigned the next number,
which thus corresponds to the products record number in a RandomAccessFile. The name
is a String that shall not exceed 100 characters. The units in stock must be a non-negative
integer, and the unit price must be a positiv number (a float).

Start for example by writing the class Product finished. It is a simple class that should not
contain much more than get and set methods for the four variables.

The programs model can be represented by the following class:

package productsprogram;

import java.io.*;
import java.util.*;
import palib.util.*;

/**
* Class which represents a product database consisting of Product objects.
* The first 4 bytes in the file is an integer that is interpreted as a signature
* for the file.
* When the file is opened, you can test this signature and thus get an indication
* that the file is a product database.
*/
public class ProductDB
{
private static final int SIGNATUR = 0x12345678;
private static final int NAMESIZE = 100;
private static final int RECORDSIZE = 2 * NAMESIZE + 10;

private String path;

/**
* Constructor that initializes the file's path. The constructor does not open
* the file, but validates the name and creates possible the file.
* If the Name can not be properly validated, the construction raises an
* exception. Following are validated
* If the file path eksistener is validated for the case of an ordinary file.
* If it this the case testes whether the file start with the correct
* signature, and is this not the case the constructor raises an exception.
* If the file path does not exist, the constructor creates a file with the
* correct signature.
* @param path The files path
* @throws IOException If the path could not be correct validated
*/
public ProductDB(String path) throws IOException {}

34
34
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

/**
* Adds a new prooduct to the file. The method assigns the product a product
* number that is the next record in the file. Thus the first product get product
* number 0.
* @param prod The product to be added to the file.
* @throws IOException If the product could not be added
*/
public void add(Product prod) throws IOException {}

/**
* Returns the product with product number pnr. If the product is not found, the
* method raises an exception.
* @param pnr The product number
* @return The product with product number pnr
* @throws IOException If the product is not found
*/
public Product select(int pnr) throws IOException {}
/**
* Returns all products in the file.
* @return AAll products in the file
*/
public ArrayList<Product> select() {}
/**
* Updates a product. The method tests whether the record on that position has
* the correct
* product number. If not raised an exception.
* @param prod The product to be updated
* @throws IOException If the product is not found
*/
public void update(Product prod) throws IOException {}

/**
* Deletes the product whose product number is pnr. The product is deleted by
* writing the -i for product number.
* @param pnr Product number for the product to be deleted
* @throws IOException If the product is not found
*/
public void delete(int pnr) throws IOException {}
}

You
You should
should note
note that
that each
each of
of the
the classs
classs methods
methods should
should both
both open
open and
and close
close the
the file.
file. You
You
should also note that the first 4 bytes in the file is a signature, which you must take
should also note that the first 4 bytes in the file is a signature, which you must take into into
account
account when
when determining
determining the
the location
location ofof each
each record.
record.

35
35
JAVA 5: FILES AND JAVA IO java.io

The applications main window should primarily display a list box with a list of all products:

Clicking on the button, you get a window where you can create a new product.

36
JAVA 5: FILES AND JAVA IO java.io
java.Io

If you double-click on an product in the list box, you get the same window, where you
can edit the product:

2.3
2.3 BYTE STREAMS
The package java.io contains several classes to byte streams and thus streams, which consists
of a sequence of bytes, and basically there are the following classes:

-- ByteArrayInputStream ByteArrayOutputStream
ByteArrayInputStream ByteArrayOutputStream
-- FileInputStream
FileInputStream FileOutputStream
-- ObjectInputStream
ObjectInputStream ObjectOutputStream
-- PipedInputStream
PipedInputStream PipedOutputStream
-- FilterInputStream
FilterInputStream FilterOutputStream

Here, the left column are input classes, which are all classes derived from an abstract class
InputStream. The right column are classes for output, and is derived from an abstract
class OutputStream. In the following I will show examples that use these classes except
PipedInputStream and PipedOutputStream that is postponed.

BYTEARRAYINPUTSTREAM AND BYTEARRAYOUTPUTSTREAM

One can think of a ByteArrayOutputStream as memory representation of an OutputStream and


a ByteArrayInputStream as a memory representation of an InputStream. The typical use of these
classes is to load the contents of a file (for example a picture) to a ByteArrayOutputStream
where the files content then can be manipulated in memory. Then the content is streamed
to a file using a ByteArrayInputStream. Consider as an example, the following test method:

private static void test06()


{
try (RandomAccessFile file = new RandomAccessFile("numbers1.dat", "rw"))
{
for (int i = 1; i <= 10; ++i) file.writeInt(i);
}

37
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io
JAVA 5: FILES AND JAVA IO java.Io

catch (IOException ex)


catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
try (RandomAccessFile file = new RandomAccessFile("numbers1.dat", "r"))
try (RandomAccessFile file = new RandomAccessFile("numbers1.dat", "r"))
{
{
for (int i = 0; i < file.length(); ++i) streamOut.write(file.readByte());
for (int i = 0; i < file.length(); ++i) streamOut.write(file.readByte());
}
}
catch (IOException ex)
catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
byte[] bytes = streamOut.toByteArray();
byte[] bytes = streamOut.toByteArray();
for (int i = 0; i < bytes.length; ++i) if ((i + 2) % 4 == 0) bytes[i] = 1;
for (int i = 0; i < bytes.length; ++i) if ((i + 2) % 4 == 0) bytes[i] = 1;
ByteArrayInputStream streamIn = new ByteArrayInputStream(bytes);
ByteArrayInputStream streamIn = new ByteArrayInputStream(bytes);
try (RandomAccessFile file = new RandomAccessFile("numbers1.dat", "rw"))
try (RandomAccessFile file = new RandomAccessFile("numbers1.dat", "rw"))
{
{
for (int b = streamIn.read(); b != -1; b = streamIn.read()) file.writeByte(b);
for (int b = streamIn.read(); b != -1; b = streamIn.read()) file.writeByte(b);
}
}
catch (IOException ex)
catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
try (RandomAccessFile file = new RandomAccessFile("numbers1.dat", "r"))
try (RandomAccessFile file = new RandomAccessFile("numbers1.dat", "r"))
{
{
for (int i = 0, n = (int)(file.length() / 4); i < n; ++i)
for (int i = 0, n = (int)(file.length() / 4); i < n; ++i)
System.out.println(file.readInt());
System.out.println(file.readInt());
}
}
catch (IOException ex)
catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

The
The method
method starts
starts by
by creating
creating aa RandomAccessFile
RandomAccessFile with
with the
the numbers
numbers from
from 11 to
to 10.
10. The
The
The method starts by creating a RandomAccessFile with the numbers from 1 to 10. The
hexadecimal
hexadecimal content
content ofof the
the file
file is:
is:
hexadecimal content of the file is:

0x00000001
0x00000001
0x00000002
0x00000002
0x00000003
0x00000003
0x00000004
0x00000004
0x00000005
0x00000005
0x00000006
0x00000006
0x00000007
0x00000007
0x00000008
0x00000008
0x00000009
0x00000009
0x0000000a
0x0000000a

38
38
38
JAVA
JAVA 5: FILES AND JAVA IO java.Io
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io

and
and the
and the fills
the fills 40
fills 40 bytes.
40 bytes. As
bytes. As the
As the next
the next step
next step the
step the content
the content
content ofof the
of the file
file isis
the file loaded
is loaded and
loaded and streamed
and streamed to
streamed to
to
aaa ByteArrayOutputStream
ByteArrayOutputStream
ByteArrayOutputStream named named streamOut.
named streamOut.
streamOut. TheThe result
result isis
The result that
is that the
that the files
the files content
files content are
content are now
are now in
now in
in
memory
memory as
as streamOut.
streamOut.
memory as streamOut.

Then
Then the
Thenthe content
thecontent of
contentof streamOut
streamOutisis
ofstreamOut referenced
isreferenced with
withaaabyte
referencedwith byte array,
bytearray, and
array,and every
andevery fourth
everyfourth byte
byteisis
fourthbyte modified:
ismodified:
modified:

byte[]
byte[] bytes
bytes =
= streamOut.toByteArray();
streamOut.toByteArray();
for
for (int
(int i
i =
= 0;
0; ii <
< bytes.length;
bytes.length; ++i)
++i) if
if ((i
((i +
+ 2)
2) %
% 4
4 ==
== 0)
0) bytes[i]
bytes[i] =
= 1;
1;

The
Theresult
The resultisis
result isthat
thatthe
that the40
the 40bytes
40 bytesrepresenting
bytes representing10
representing 10integers
10 integersnow
integers noware
now arethe
are thenumbers
the numbers257,
numbers 257,258,
257, 258,,
258, ,266:
, 266:
266:

0x00000101
0x00000101
0x00000102
0x00000102
0x00000103
0x00000103
0x00000104
0x00000104
0x00000105
0x00000105
0x00000106
0x00000106
0x00000107
0x00000107
0x00000108
0x00000108
0x00000109
0x00000109
0x0000010a
0x0000010a

39
39
39
JAVA
JAVA5:
5:FILES
FILESAND
ANDJAVA
JAVAIOIO java.io
java.Io
JAVA 5: FILES AND JAVA IO java.Io

After
Aftereach
After eachbyte
each byteisisismanipulated
byte manipulatedthe
manipulated thearrray
the arrrayisisisencapsulated
arrray encapsulatedin
encapsulated inaaaByteArrayInputStream,
in ByteArrayInputStream,and
ByteArrayInputStream, and
and
the
theresult
the resultisisiswritten
result writtenback
written backto
back tothe
to thefile.
the file.
file.

The
Theabove
The aboveexample
above exampleof
example ofusing
of usingaaaByteArrayOutputStream
using ByteArrayOutputStreamand
ByteArrayOutputStream andaaaByteArrayInputStream
and ByteArrayInputStreamisisisnot
ByteArrayInputStream not
not
typical
typicaland
typical andshould
and shouldonly
should onlyshow
only showthe
show thesyntax.
the syntax.Later
syntax. LaterIIIwill
Later willshow
will showexamples,
show examples,where
examples, wherethese
where theseclasses
these classes
classes
are
areimportant.
are important.
important.

FILEINPUTSTREAM
FILEINPUTSTREAMAND
FILEINPUTSTREAM ANDFILEOUTPUTSTREAM
AND FILEOUTPUTSTREAM
FILEOUTPUTSTREAM
Of
Ofthe
Of theabove
the aboveclasses
above classesto
classes tobyte
to bytestreams
byte streamsare
streams areFileInputStream
are FileInputStreamand
FileInputStream andFileOutputStream
and FileOutputStreamprobably
FileOutputStream probablythe
probably the
the
most important
most important
most important asas it is classes
as itit isis classes that
classes that can
that can stream
can stream bytes
stream bytes from
bytes from and
from and to
and to a file.
to aa file. I will
file. II will show
will show as
show as an
as an
an
example
exampleaaamethod
example methodthat
method thatencrypts
that encryptsthe
encrypts thecontent
the contentof
content ofaaafile.
of file.The
file. Theexample
The exampleisisissuitable
example suitableto
suitable todemonstrate
to demonstrate
demonstrate
how
howto
how tomanipulate
to manipulatethe
manipulate thecontent
the contentof
content ofaaafile,
of file,but
file, butthe
but thealgorithm
the algorithmcan
algorithm cannot
can notbe
not beused
be usedfor
used forpractical
for practical
practical
encryption of
encryption of
encryption files,
of files, since
files, since it is easy
since itit isis easy to
easy to determine
to determine
determine the the key.
the key. The
key. The procedure
The procedure is
procedure isis as as follows:
as follows:
follows:

AAAbyte
bytecan
byte canhave
can have256
have 256different
256 differentvalues
different valuesand
values andIIIstarts
and startswith
starts withaaabyte
with bytearray
byte arraywith
array with256
with 256places
256 placesand
places and
and
initializes
initializesthe
initializes thearray
the arraywith
array withthe
with thevalues
the values0255
values 0255(below
0255 (belowwritten
(below writtenin
written inhexadecimal):
in hexadecimal):
hexadecimal):

00 01
00 01 02
02 03
03 04
04 05
05 06
06 07
07 08
08 09
09 0a
0a 0b
0b 0c
0c 0d
0d 0e
0e 0f
0f
10 11
10 11 12
12 13
13 14
14 15
15 16
16 17
17 18
18 19
19 1a
1a 1b
1b 1c
1c 1d
1d 1e
1e 1f
1f
20
20 2121 22
22 23
23 24
24 25
25 26
26 27
27 28
28 29
29 2a
2a 2b
2b 2c
2c 2d
2d 2e
2e 2f
2f
30 31
30 31 32
32 33
33 34
34 35
35 36
36 37
37 38
38 39
39 3a
3a 3b
3b 3c
3c 3d
3d 3e
3e 3f
3f
40
40 4141 42
42 43
43 44
44 45
45 46
46 47
47 48
48 49
49 4a
4a 4b
4b 4c
4c 4d
4d 4e
4e 4f
4f
50 51
50 51 52
52 53
53 54
54 55
55 56
56 57
57 58
58 59
59 5a
5a 5b
5b 5c
5c 5d
5d 5e
5e 5f
5f
....
....
f0 f1
f0 f1 f2 f3
f2 f3 f4
f4 f5
f5 f6
f6 f7
f7 f8
f8 f9
f9 fa
fa fb
fb fc
fc fd
fd fe
fe ff
ff

Then
ThenIIIperformes
performesaaapermutation
permutationof ofthe
thearray
array(corresponding
(correspondingtotoaaanumber
numberof
ofswaps
swapsof
ofpair
pair
Then performes permutation of the array (corresponding to number of swaps of pair
ofofelements).
elements).The
Theresult
resultcould,
could,for
forinstance
instancebe:
be:
of elements). The result could, for instance be:

00 01
00 01 32
32 03
03 04
04 05
05 38
38 07
07 08
08 09
09 0a
0a 0b
0b 0c
0c 0d
0d 0e
0e 0f
0f
10 11
10 11 12
12 13
13 14
14 15
15 16
16 17
17 18
18 19
19 1a
1a 30
30 1c
1c 1d
1d 1e
1e 1f
1f
20
20 2121 22
22 23
23 24
24 25
25 26
26 27
27 28
28 29
29 2a
2a 2b
2b 5c
5c 2d
2d 2e
2e 2f
2f
1b 31
1b 31 02
02 33
33 34
34 35
35 36
36 37
37 06
06 39
39 3a
3a 3b
3b 3c
3c 3d
3d 3e
3e 3f
3f
40
40 4141 42
42 43
43 4e
4e 45
45 46
46 47
47 48
48 49
49 4a
4a 4b
4b 4c
4c 4d
4d 44
44 4f
4f
50 51
50 51 52
52 53
53 54
54 55
55 56
56 57
57 58
58 59
59 5a
5a 5b
5b 2c
2c 5d
5d 5e
5e 5f
5f
....
....
f0 f1
f0 f1 f2 f3
f2 f3 f4
f4 f5
f5 f6
f6 f7
f7 f8
f8 f9
f9 fa
fa fb
fb fc
fc fd
fd fe
fe ff
ff

Thepermuted
The
The permutedarray
permuted arrayisisisthen
array thenthe
then theencryption
the encryptionkey.
encryption key.Consider
key. Considerthe
Consider thefollowing
the followinginteger:
following integer:
integer:

0x021b2c30
0x021b2c30

4040
40
JAVA
JAVA 5:
JAVA 5: FILES
5: FILES AND
FILES AND JAVA
AND JAVA IO
JAVA IO
IO java.io
java.Io
java.Io

that
that isis
that is the
the number
the number 35335216.
number 35335216. IfIf
35335216. If we
we now
we now must
now must encrypt
must encrypt this
encrypt this number
this number with
number with the
with the above
the above key
above key
key
the
the principle is that each byte is used as an index to the key and replaced
the principle is that each byte is used as an index to the key and replaced with what the
principle is that each byte is used as an index to the key and replaced with
with what
what the
the
key
key contains
contains at
at that
that index:
key contains at that index:index:

0x32305c1b
0x32305c1b

which
which isis
which is the
the number
the number 842030107,
number 842030107, that
842030107, that isis
that is aaa completely
completely different
completely different number.
different number. Its
number. Its fine
Its fine to
fine to be
to be able
be able
able
to
to encrypt
to encrypt data,
encrypt data, but
data, but itit
but it isis
is not
not much
not much worth
much worth unless
worth unless you
unless you can
you can also
can also decrypt
also decrypt the
decrypt the data.
the data. IfIf
data. If you
you
you
has
has the key, it is simple. For each byte you can find its index in the key and the byte isis
has the
the key,
key, it
it is
is simple.
simple. For
For each
each byte
byte you
you can
can find
find its
its index
index in
in the
the key
key and
and the
the byte
byte is
replaced
replaced with
with the
the
replaced with the index: index:
index:

0x021b2c30
0x021b2c30

and
and you
and you are
you are back
are back to
back to the
to the number
the number that
number that was
that was originally
was originally encrypted.
originally encrypted.
encrypted.

Consider
Consider the
Consider the following
the following test
following test method:
test method:
method:

private
private static
static void
void test07()
test07()
{
{
String
String path0
path0 == "text0";
"text0";
String
String path1 =
path1 = "text1";
"text1";
String
String path2 = "text2";
path2 = "text2";
FileOutputStream
FileOutputStream streamOut
streamOut == null;
null;
try
try
{
{
streamOut
streamOut = = new
new FileOutputStream(path0);
FileOutputStream(path0);
String
String navn = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
navn = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
byte[]
byte[] bytes
bytes = = navn.getBytes();
navn.getBytes();
streamOut.write(bytes);
streamOut.write(bytes);
}
}
catch
catch (IOException
(IOException ex)ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
finally
finally
{
{
if
if (streamOut
(streamOut != != null)
null) try
try {
{ streamOut.close();
streamOut.close(); }
} catch
catch (Exception
(Exception e)
e) {}
{}
}
}
printTekst(path0);
printTekst(path0);
int[]
int[] key
key =
= createKey();
createKey();
crypt(path0,
crypt(path0, path1,
path1, key);
key);
printTekst(path1);
printTekst(path1);
decrypt(path1,
decrypt(path1, path2,
path2, key);
key);
printTekst(path2);
printTekst(path2);
}
}

41
41
41
JAVA
JAVA 5: FILES AND JAVA IO java.Io
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io

The
The first
The first part
first part of
part of the
of the method
the method writes
writes aaa string
method writes string
string

String
String navn
navn =
= "ABCDEFGHIJKLMNOPQRSTUVXYZ";
"ABCDEFGHIJKLMNOPQRSTUVXYZ";

to
to
to anan FileOutputStream.
an FileOutputStream.
FileOutputStream. You You should
You should note,
should note, how
note, how
how to to create
create aaa FileOutputStream,
to create FileOutputStream,
FileOutputStream, converts converts
converts thethe
the
string
string to
to a
a byte
byte array
array and
and then
then write
write that
that array
array to
to the
the file.
file. The
The file
file is
is
string to a byte array and then write that array to the file. The file is called text0 and saved called
called text0
text0 and
and saved
saved
in
in the
in the current
the current directory.
directory. IfIf
current directory. you
If you examine
you examine
examine thethe file,
the file, you
file, you will
you will see
will see that
that itit
see that takes
it takes
takes upup 31
up 31 bytes,
31 bytes, which
bytes, which
which
is perhaps
isis perhaps
perhaps notnot what
not what one
what one would
one would expect,
would expect, but
expect, but the
but the reason
the reason
reason is, is, that
is, that the
that the String
the String classs
String classs getBytes()
classs getBytes()
getBytes()
method
method converts
converts aaa string
method converts string to
to aaa byte
string to byte array
byte array using
array using the
using the default
the default character
default character encoding
character encoding
encoding whichwhich
which isis UTF8.
is UTF8.
UTF8.
The
The string takes up 28 characters that except for the last three are encoded
The string takes up 28 characters that except for the last three are encoded as a single byte,
string takes up 28 characters that except for the last three are encoded as
as aa single
single byte,
byte,
while
while the
the last
last three
three each
each uses
uses 22 bytes.
bytes. Therefore
Therefore the
the 25
25
while the last three each uses 2 bytes. Therefore the 25 + 6 = 31 bytes. +
+ 66 =
= 31
31 bytes.
bytes.

The
The program
The program also
program also has
has aaa method
also has method that
method that reads
that reads the
reads the content
the content of
of aaa stream
content of stream (a
stream (a file),
(a file), interprets
file), interprets the
interprets the
the
content
content as
as text
text and
and prints
prints the
the text
text on
on the
the screen:
screen:
content as text and prints the text on the screen:

private
private static
static void
void printTekst(String
printTekst(String path)
path)
{
{
FileInputStream
FileInputStream stream
stream =
= null;
null;
try
try
{
{
stream
stream =
= new
new FileInputStream(path);
FileInputStream(path);

Join the best at Top masters programmes


3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
1st place: MSc International Business
School of Business and 1st place: MSc Financial Economics
2nd place: MSc Management of Learning

Economics! 2nd place: MSc Economics


2nd place: MSc Econometrics and Operations Research
2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier Beste Studies ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Masters Open Day: 22 February 2014

www.mastersopenday.nl

42
42
42
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

ByteArrayOutputStream bytes = new ByteArrayOutputStream();


for (int b = stream.read(); b != -1; b = stream.read()) bytes.write(b);
System.out.println(new String(bytes.toByteArray()));
}
catch (IOException ex)
{
System.out.println(ex);
}
finally
{
if (stream != null) try { stream.close(); } catch (Exception e) {}
}
}

In
In this
this case,
case, aa FileInputStream
FileInputStream is
is opened,
opened, and
and the
the files
files content
content are
are read
read to
to aa ByteArrayOutputStream.
ByteArrayOutputStream.
This
This stream
stream is is then
then converted
converted to to aa string
string that
that is is printed
printed onon the
the screen.
screen. The
The method
method is
is used
used
in
in the
the test
test method
method test07()
test07() to
to print
print the
the files
files content
content onon the
the screen.
screen.

The
The rest
rest of
of the
the test
test method
method then
then performs
performs anan encryption
encryption of
of the
the files
files text
text to
to the
the file
file text1
text1
and
and prints
prints the
the content
content of
of this
this file
file on
on the
the screen.
screen. The
The following
following method
method creates
creates the
the key
key by
by
swapping
swapping random
random elements
elements in
in the
the array
array key
key 1000
1000 times:
times:

private static int[] createKey()


{
int[] key = new int[256];
for (int i = 0; i < key.length; ++i) key[i] = i;
Random rand = new Random();
for (int n = 0; n < 1000; ++n)
{
int i = rand.nextInt(key.length);
int j = rand.nextInt(key.length);
if (i != j)
{
int t = key[i];
key[i] = key[j];
key[j] = t;
}
}
return key;
}

In principle, it is possible to create 256! keys that are a vastly large number, so it is a
hopeless task to guess the key, but in return it is relatively easy to determine the key in
plain text analysis.

43
43
JAVA5:5:FILES
JAVA FILES ANDJAVA
JAVA IO java.Io
JAVA 5: FILESAND
AND JAVAIO
IO java.io
java.Io

Thefollowing
The following classisisused
used to encryptaafile:
file:
The followingclass
class is usedtotoencrypt
encrypt a file:

class InCrypter extends FilterOutputStream


class InCrypter extends FilterOutputStream
{
{
private int[] key;
private int[] key;

public InCrypter(OutputStream stream, int[] key)


public InCrypter(OutputStream stream, int[] key)
{
{
super(stream);
super(stream);
this.key = key;
this.key = key;
}
}

public void write(int b) throws IOException


public void write(int b) throws IOException
{
{
out.write(key[b]);
out.write(key[b]);
}
}
}
}

Theclass
The classinherits
inheritsFilterOutputStream,
FilterOutputStream,aastream
streamthat
thatfilters
filters(manipulates)
(manipulates)the
thebytes
bytessent
senttoto
The class inherits FilterOutputStream, a stream that filters (manipulates) the bytes sent to
themethod
the methodwrite(),
write(),which
whichcollects
collectsthe
theindividual
individualbytes
bytesininaabuffer
bufferbefore
beforebeing
beingprinted
printedtoto
the method write(), which collects the individual bytes in a buffer before being printed to
anOutputStream.
an OutputStream.InInthisthiscase,
case,the
theOutputStream
OutputStreamisissent
sentasasaaparameter
parametertotothe
theconstructor
constructor
an OutputStream. In this case, the OutputStream is sent as a parameter to the constructor
togetherwith
together withthe
thekey,
key,and
andthethestream
streamobject
objectisistransferred
transferredtotothe
thebase
baseclass.
class.The
Thewrite()
write()
together with the key, and the stream object is transferred to the base class. The write()
methodisisknown
method knownby bythe
thename
nameout.
out.
method is known by the name out.

Withthis
With thisclass
classthe
thefile
filecan
canbe
beencrypted
encryptedininthe
thefollowing
followingway:
way:
With this class the file can be encrypted in the following way:

private static void crypt(String path1, String path2, int[] key)


private static void crypt(String path1, String path2, int[] key)
{
{
FileInputStream in = null;
FileInputStream in = null;
InCrypter inCrypter = null;
InCrypter inCrypter = null;
try
try
{
{
in = new FileInputStream(path1);
in = new FileInputStream(path1);
inCrypter = new InCrypter(new FileOutputStream(path2), key);
inCrypter = new InCrypter(new FileOutputStream(path2), key);
for (int b = in.read(); b != -1; b = in.read()) inCrypter.write(b);
for (int b = in.read(); b != -1; b = in.read()) inCrypter.write(b);
}
}
catch (IOException ex)
catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
finally
finally
{
{
if (in != null) try { in.close(); } catch (IOException e) {}
if (in != null) try { in.close(); } catch (IOException e) {}
if (inCrypter != null) try { inCrypter.close(); } catch (IOException e) {}
if (inCrypter != null) try { inCrypter.close(); } catch (IOException e) {}
}
}
}
}

44
44
44
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io

path1 is the name of the file to be encrypted, and it is opened as a FileInputStream. path2 is
the name of the file, that must contain the encrypted data and opens as a FileOutputStream
used as a paramterer to an InCrypter object. After this happens the encryption by reading
the input file and writes it to the output file using the FilterOutputStream object. You should
note that when this stream is closed in the finally block, also the OutputStream is closed so
the content is written physically to the file.

Decryption of the file takes place in principle in the same way. I first defines a FilterInputStream
as a filter for an InputStream:

class DeCrypter extends FilterInputStream


{
private int[] key;

public DeCrypter(InputStream stream, int[] key)


{
super(stream);
int[] map = new int[256];
for (int i = 0; i < map.length; ++i) map[key[i]] = i;
this.key = map;
}

> Apply now

redefine your future


AxA globAl grAduAte
progrAm 2015
- Photononstop

axa_ad_grad_prog_170x115.indd 1 19/12/13 16:36

45
45
JAVA 5: FILES AND JAVA IO java.io
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.Io
java.Io

public int read()


public int read() throws
throws IOException
IOException
{
{
int
int value
value =
= in.read();
in.read();
return
return (value ==
(value == -1)
-1) ?
? -1
-1 :
: key[value];
key[value];
}
}
}
}

The
The constructor
constructor has
has this
this time
time an
an InputStream
InputStream as as aa parameter,
parameter, but
but also
also the
the constructor
constructor inverts
inverts
the
the key
key to
to make
make it
it easier
easier to to decrypt
decrypt the
the file.
file. The
The method
method read()
read() reads
reads the
the next
next byte
byte in
in the
the
input stream and is it a byte (and not EOF), the method returns the
input stream and is it a byte (and not EOF), the method returns the inverted key. The inverted key. The
following
following method
method can
can be be used
used to
to decrypt
decrypt anan encrypted
encrypted file:
file:

private
private static
static void
void decrypt(String
decrypt(String path1,
path1, String
String path2,
path2, int[]
int[] key)
key)
{
{
DeCrypter
DeCrypter deCrypter
deCrypter = = null;
null;
FileOutputStream out
FileOutputStream out == null;
null;
try
try
{
{
deCrypter
deCrypter = = new
new DeCrypter(new
DeCrypter(new FileInputStream(path1),
FileInputStream(path1), key);
key);
out =
out = new
new FileOutputStream(path2);
FileOutputStream(path2);
for
for (int
(int b
b =
= deCrypter.read();
deCrypter.read(); bb !=
!= -1;
-1; b
b =
= deCrypter.read())
deCrypter.read()) out.write(b);
out.write(b);
}
}
catch
catch (IOException
(IOException ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
finally
finally
{
{
if
if (deCrypter
(deCrypter !=
!= null)
null) try
try {
{ deCrypter.close();
deCrypter.close(); }} catch
catch (IOException
(IOException e)
e) {}
{}
if (out
if (out !=
!= null)
null) try
try {
{ out.close();
out.close(); }} catch
catch (IOException
(IOException e)e) {}
{}
}
}
}
}

Here path1 is the name of the file to be decrypted, and path2 is the name of the decrypted
file.
file. The
The method
method works
works in
in principle
principle in
in the
the the
the same
same manner
manner as
as the
the method
method crypt(),
crypt(), only
only
with the difference that it use a FilterInputStream.

If
If you
If you run
you runthe
run theprogram,
the program, you get
youyou
program, the
the following
get get following result:
result:result:
the following

ABCDEFGHIJKLMNOPQRSTUVXYZ
ABCDEFGHIJKLMNOPQRSTUVXYZ
##
###
# #
#
H#[3-
H#[3-
F
F~z~g~
~z~g~
ABCDEFGHIJKLMNOPQRSTUVXYZ
ABCDEFGHIJKLMNOPQRSTUVXYZ

If you examines
examines thethree
three filesusing
using Filesand
and you should note thatthree
all three have
files havesame
the
If
If you
you examines the files using Files
the three files Files and you
you should
should note
note that
that all
all three files
files have the
the same size
size
same
(31 size
bytes).
(31 bytes).(31 bytes).

Exercise 2
46
46
46
Write a program named Copy that should be performed as a command and works in much the same
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io

EXERCISE 22
EXERCISE
Write aa program
Write program named
named Copy
Copy that
that should
should bebe performed
performed as as aa command
command and and works
works in in much
much
the same
the same way
way asas the
the command
command cp cp in
in Linux,
Linux, where
where the
the command
command lineline specifies
specifies the
the file
file
source to
source to be
be copied,
copied, and
and the
the name
name of of the
the file
file destination
destination as
as itit should
should be
be copied
copied to.to.
The source
The source file
file must
must bebe an
an InputStream
InputStream andand the
the destination
destination must
must be
be an an OutputStream.
OutputStream.

When the
When the program
program isis finished,
finished, you
you must
must test
test it,
it, and
and preferably
preferably with
with files
files of
of different
different types,
types,
such as
such as aa document
document andand aa picture.
picture.

DATA STREAMS
DATA STREAMS

Byte streams
Byte streams areare the
the basic
basic streams,
streams, and
and inin principle,
principle, all
all streams
streams are
are byte
byte streams,
streams, but
but there
there are are
otherclasses
other classesthat
thatmake
makeititeasy
easytotostream
streamother
otherprimitive
primitivetypes
typestotoaafile.
file.ItItisisaaDataOutputStream
DataOutputStream
which isis derived
which derived fromfrom FilterOutputStream
FilterOutputStream and and DataInputStream
DataInputStream that that isis derived
derived from
from the the
FilterInputStream. II will
FilterInputStream. will also
also mention
mention aa BufferedOutputStream
BufferedOutputStream and and aa BufferedInputStream,
BufferedInputStream,
which also
which also are
are derived
derived from
from thethe classes
classes FilterOutputStream
FilterOutputStream and and FilterInputStream.
FilterInputStream. In In general,
general,
the data
the data streams
streams works
works asas an
an OutputStream
OutputStream and and an
an InputStream
InputStream in in the
the sense
sense that
that they
they calls
calls
the operating
the operating system
system forfor each
each byte
byte to
to be
be written
written and
and forfor each
each byte
byte to to be be reading.
reading. ItIt isis not
not
particularly effective
particularly effective and,
and, therefore
therefore the
the classes
classes BufferedOutputStream
BufferedOutputStream and and BufferedInputStream,
BufferedInputStream,
that assign
that assign buffers
buffers to to an
an OutputStream
OutputStream and and anan InputStream.
InputStream.

Consider the
Consider the following
following test
test method:
method:

private static void test08()


{
try (DataOutputStream stream =
new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data"))))
{
stream.writeInt(123);
stream.writeDouble(Math.PI);
stream.writeUTF("ge Srensen");
stream.writeLong(Long.MAX_VALUE);
}
catch (IOException ex)
{
System.out.println(ex);
}
try (DataInputStream stream =
new DataInputStream(new BufferedInputStream(new FileInputStream("data"))))
{
System.out.println(stream.readInt());
System.out.println(stream.readDouble());
System.out.println(stream.readUTF());

47
47
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

System.out.println(stream.readLong());
}
catch (IOException ex)
{
System.out.println(ex);
}
}

First the method opens a FileOutputStream called data. It is then encapsulated in a


BufferedOutputStream, which in turn is encapsulated in a DataOutputStream. Then the
method writes an int, a double, a String and a long to the file. You should note that a
DataOutputStream has write methods for all the primitive types and also the type String.
Here, the method writeInt() write 4 bytes to the file, while the method writeDouble() writes
8 bytes. The method writeUTF() writes a string converted with an UTF8 encoding. The
string fills in this case, 12 characters, and because of the characters and it will therefore
be encoded as 14 bytes, and the method should therefore write

4 + 8 + 14 + 8 = 34 bytes

48
48
JAVA 5: FILES AND JAVA IO java.io

to the file. If you examine the file, you will find that it takes up 36 bytes. The reason is
that the method writeUTF() adds two additional bytes (the first two bytes), which indicates
the number of bytes written to the file (the length of the string). It is necessary to read
the string again.

The last part of the test method reads the content of the file again, and here you must note
that a DataInputStream has read-methods for all the primitive data types. For example the
method readDouble() that reads the next eight bytes from the location where the file pointer
is and convert the bytes to a double. Similarly, readUTF() to reads the first two bytes, and
from these determines how many bytes to be read.

EXERCISE 3
You must write a program that has a method that prints 1000000 random numbers of
the type double to a file. The numbers should be written using a DataOutputStream, but
without using a BufferedOutputStream. When the method writes data to the file, it must
at the same time determines the sum of the numbers and print the value on the screen.

The program must also have a method that reads the numbers in the above file and
determines their sum. The numbers must be read using a DataInputStream, but without
using a BufferedInputStream. Finally, the method must print the sum on the screen and it
would like to be the same number as in the first method.

Finally, try to change the above methods, so the first uses a BufferedOutputStream and the
other uses a BufferedInputStream. Try to observe an increased efficiency. If not, try to increase
the number of numbers to 10000000.

EXERCISE 4
You have to write the same program as in exercise 2, but this time you must encapsulate
the two streams respectively in a BufferedOutputStream and a BufferedInputStream.

Can you observe an improvement?

49
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.io
java.Io

2.4
2.4 OBJECT
OBJECT SERIALIZATION
SERIALIZATION
In
In the
the examples
examples in in the
the previous
previous books
books II have
have usedused serialization
serialization of of objects
objects asas anan easy
easy way
way
to
to store
store data
data in in aa file.
file. II will
will now
now take
take aa closer
closer look
look atat how
how itit works.
works. In In principle
principle itit isis aa
matter
matter of of stream
stream an an objects
objects bytes
bytes to
to aa ByteStream,
ByteStream, but but itit isis not
not necessarily
necessarily simple.
simple. IfIf you
you
consider
consider a DataStream, it is simple because for the primitive types, you know how muchaa
a DataStream, it is simple because for the primitive types, you know how much
datalement
datalement fills,fills, and
and then
then exactly
exactly how
how many
many bytes
bytes toto be
be written
written or or read.
read. This
This isis expressed
expressed
by
bythetheclasses
classesDataOutputStream
DataOutputStreamand andDataInputStream
DataInputStreamthat thathas hasspecific
specificmethods
methodsfor foreach
eachof of
the primitive data types. When you look at a String (which is an object)
the primitive data types. When you look at a String (which is an object) it is necessary with it is necessary with
aalittle
littlemore
moresincesinceititisisnecessary
necessaryalsoalsototosave,
save,how
howmanymanybytesbytesthe thestring
stringfills.
fills.ItItisisnecessary
necessary
to
to read
read the
the string
string again.
again. The The situation
situation isis even
even more
more complex
complex ifif therethere isis any
any object,
object, since
since
one
one does
does not
not know
know whatwhat such
such anan object
object fills,
fills, and
and when
when itit may may bebe composed
composed of of primitive
primitive
types
types and objects that in turn can consist of primitive types and objects, and it mayrepeat
and objects that in turn can consist of primitive types and objects, and it may repeat
atat an arbitrary depth.
an arbitrary depth.

InInorder
ordertotoload
loadan anobject
objectfrom
fromaafile,
file,ititisisnecessary,
necessary,together
togetherwith
withthetheobjects
objectsdata
datatotostore
store
information about the objects structure, and as an object, in principle,
information about the objects structure, and as an object, in principle, is a hierarchical is a hierarchical
structure
structure there
there must
must bebe stored
stored information
information about about the
the entire
entire structure,
structure, such
such that
that the
the object
object
can
can be be restored
restored when
when itit isis deserialized.
deserialized. ItIt isis not
not free,
free, to
to serialize
serialize and
and deserialize
deserialize objects
objects
and
and isis not
not necessarily
necessarily effective
effective and
and isis done
done using
using aa technique
technique called
called reflection,
reflection, which
which are
are
explained in a recent book. For this reason, Java supports three types of
explained in a recent book. For this reason, Java supports three types of serialization, whichserialization, which
isis illustrated
illustrated inin the
the following
following examples.
examples.

In
Inorder
orderthat
thatan
anobject
objectcan
canbebeserialized,
serialized,ititmust
mustimplement
implementthe theinterface
interfaceSerializable.
Serializable.ItItisisaa
simple
simpleinterface
interfacewithout
withoutfields
fieldsor
ormethods.
methods.IfIfyou
youtrytryto
toserialize
serializean
anobject
objectwhose
whoseclass
classisisnot
not
Serializable you get an Exception. As an example is shown a class that is defined Serializable:
Serializable you get an Exception. As an example is shown a class that is defined Serializable:

class Person implements Serializable


{
private String name;
private Calendar fdate;
private double sats;
private transient int hours = 0;

public Person(String name, Calendar fdate, double sats)


{
this.name = name;
this.fdate = fdate;
this.sats = sats;
}

50
50
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

public String getName()


{
return name;
}

public int getAge()


{
Calendar dato = Calendar.getInstance();
int age = dato.get(Calendar.YEAR) fdate.get(Calendar.YEAR);
if ((dato.get(Calendar.MONTH) + 1) * 100 + dato.get(Calendar.DATE) >=
(fdate.get(Calendar.MONTH) + 1) * 100 + fdate.get(Calendar.DATE)) ++age;
return age;
}

public double getPay()


{
return hours * sats;
}

public void add(int hours)


{
this.hours += hours;
}

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

51
51
JAVA 5: FILES AND JAVA IO java.io
JAVA 5:
JAVA 5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.Io
java.Io

public String
public String toString()
toString()
{
{
return name
return name + String.format(",
+ String.format(", %d
%d years",
years", getAge());
getAge());
}
}
}
}

The class
The class has
has four
four instance
instance variables.
variables. ItIt can
can bebe serialized
serialized asas the
the first
first variable
variable has
has the
the type
type
String, which
String, which isis Serializable,
Serializable, the
the other
other isis of
of the
the type
type Calendar
Calendar (and
(and must
must represent
represent aa persons
persons
date of
date of birth)
birth) isis also
also Serializable,
Serializable, while
while thethe third
third isis aa double
double (and
(and all
all variables
variables of
of aa primitive
primitive
types can
types can immediately
immediately be be serialized).
serialized). TheThe variable
variable willwill represent
represent anan hourly
hourly rate.
rate. The
The last
last
variable represents
variable represents the the number
number of of hours,
hours, and and itit isis defined
defined transient.
transient. Such
Such aa variable
variable isis not
not
serialized, and
serialized, and the the meaning
meaning isis that
that you
you then then cancan specify
specify that
that variables
variables or
or objects
objects ofof any
any
reason not
reason not should
should be be serialized.
serialized.

The following
The following method
method creates
creates aa Person
Person object,
object, assigns
assigns thethe person
person 20
20 hours,
hours, and
and then
then
prints the
prints the object.
object. Next,
Next, the
the object
object isis serialized
serialized to
to aa file.
file. An
An object
object isis serialized
serialized with
with an
an
ObjectOutputStream (which
ObjectOutputStream (which as
as parameter
parameter has has an
an OutputStream)
OutputStream) and and the
the method
method writeObject():
writeObject():

private static
private static void
void test09()
test09()
{
{
try (ObjectOutputStream
try (ObjectOutputStream stream
stream ==
new ObjectOutputStream(new
new ObjectOutputStream(new FileOutputStream("person")))
FileOutputStream("person")))
{
{
Person pers
Person pers =
=
new Person("Carlo Jensen", new
new Person("Carlo Jensen", new GregorianCalendar(1949,
GregorianCalendar(1949, 0,
0, 23),
23), 225);
225);
pers.add(20);
pers.add(20);
print(pers);
print(pers);
stream.writeObject(pers);
stream.writeObject(pers);
}
}
catch (IOException
catch (IOException ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
try (ObjectInputStream
try (ObjectInputStream stream
stream =
=
new ObjectInputStream(new FileInputStream("person")))
new ObjectInputStream(new FileInputStream("person")))
{
{
Person pers
Person pers =
= (Person)stream.readObject();
(Person)stream.readObject();
print(pers);
print(pers);
}
}
catch (ClassNotFoundException
catch (ClassNotFoundException ex)ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}

52
52
52
JAVA 5: FILES AND JAVA IO java.io
JAVA 5:
JAVA 5: FILES AND
AND JAVA IO
IO java.Io
JAVA 5: FILES
FILES AND JAVA
JAVA IO java.Io
java.Io

catch (IOException
catch (IOException ex)
catch (IOException ex)
ex)
{
{
{
System.out.println(ex);
System.out.println(ex);
System.out.println(ex);
}
}
}
}
}
}

Afterthe
After theobject
objectisis
is serialized
serializeditit
it isdeserialized
deserializedagain
againwith
withan
anObjectInputStream,
ObjectInputStream,after
afterwhich
whichitit
it
After
After the object isserialized
the object serialized itisis
is deserialized
deserialized again
again with
with an
an ObjectInputStream,
ObjectInputStream, after
after which
which it
isprinted
isis printedon onthe
thescreen.
screen.The Theobject
objectisis
is read
readwith
withreadObject(),
readObject(),and
andyou
youshould
shouldnote
notethetheneed
need
is printed
printed onon the
the screen.
screen. The object isread
The object read with
with readObject(),
readObject(), and
and you
you should
should note
note the
the need
need
foraaatypecast.
for
for typecast.IfIf
typecast. Ifitit
itnot
notisis
not ispossible,
possible,you
possible, youget
you getaaaClassNotFoundException.
get ClassNotFoundException.The
ClassNotFoundException. Theprint()
The print()method
print() methodis:is:
method is:
for a typecast. If it not is possible, you get a ClassNotFoundException. The print() method is:

private static
private static void print(Person
print(Person pers)
private static void
void print(Person pers)
pers)
{
{
{
System.out.println(pers);
System.out.println(pers);
System.out.println(pers);
System.out.println("Pay: "
System.out.println("Pay: " + pers.getPay());
pers.getPay());
System.out.println("Pay: " ++ pers.getPay());
}
}
}

and
andifif
ifthe
thetest
testmethod
methodisis
isperformed,
performed,you
youget
getthe
theresult:
result:
and
and if the
the test
test method
method is performed,
performed, you
you get
get the
the result:
result:

Carlo Jensen,
Carlo Jensen, 68 years
68 years
Carlo Jensen, 68 years
Pay:
Pay: 4500.0
Pay: 4500.0
4500.0
Carlo Jensen,
Carlo Jensen, 68 years
68 years
Carlo Jensen, 68 years
Pay:
Pay: 0.0
Pay: 0.0
0.0

Youshould
You shouldnote
notethat
thatthe
thevalue
valueofof
of the
thevariable
variablehours
hoursisis
is not
notserialized.
serialized.
You should
You should note
note that
that the
the value the variable
value ofthe variable hours not serialized.
hours isnot serialized.

SERIALIZESMULTIPLE
SERIALIZES MULTIPLEOBJECTS
OBJECTS
SERIALIZES MULTIPLE
SERIALIZES MULTIPLE OBJECTS
OBJECTS
Thefollowing
The followingmethod
methodalso
alsoserialize
serializePerson
Personobjects
objects(three
(threeobjects),
objects),and
andshould
shouldshow
showthat
thatitit
it
The following
The following method
method also
also serialize
serialize Person
Person objects
objects (three
(three objects),
objects), and
and should
should show
show that
that it
ispossible
isis possibletoto
to serialize
serializemultiple
multipleobjects
objectsinin
in the
thesame
samefile:
file:
is possible serialize multiple
possible toserialize multiple objects the same
objects inthe same file:
file:

private static
private static void test10()
test10()
private static void
void test10()
{
{
{
Person[] pers
Person[] pers = {{
Person[] pers == {
new
new Person("Carlo Jensen", new
new GregorianCalendar(1949, 0, 0, 23), 225),
225),
new Person("Carlo
Person("Carlo Jensen",
Jensen", new GregorianCalendar(1949,
GregorianCalendar(1949, 0, 23),
23), 225),
new Person("Gudrun
new Person("Gudrun Andersen", newnew GregorianCalendar(1963, 10,
10, 3), 325),
325),
new Person("Gudrun Andersen",
Andersen", new GregorianCalendar(1963,
GregorianCalendar(1963, 10, 3),3), 325),
new
new Person("Abelone Srensen", new GregorianCalendar(1972, 3, 13), 375) };
new Person("Abelone
Person("Abelone Srensen",
Srensen", new
new GregorianCalendar(1972,
GregorianCalendar(1972, 3,
3, 13),
13), 375)
375) };
};
try (ObjectOutputStream
try (ObjectOutputStream stream
stream ==
try (ObjectOutputStream stream =
new ObjectOutputStream(new
new ObjectOutputStream(new FileOutputStream("personer")))
new ObjectOutputStream(new FileOutputStream("personer")))
FileOutputStream("personer")))
{
{
{
for (Person
for (Person p :: pers) stream.writeObject(p);
stream.writeObject(p);
for (Person pp : pers)
pers) stream.writeObject(p);
}
}
}
catch (IOException
catch (IOException ex)
catch (IOException ex)
ex)
{
{
{
System.out.println(ex);
System.out.println(ex);
System.out.println(ex);
}
}
}

53
53
53
53
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

try (ObjectInputStream stream =


new ObjectInputStream(new FileInputStream("personer")))
{
for (;;)
{
Person p = (Person)stream.readObject();
System.out.println(p);
}
}
catch (EOFException ex)
{
}
catch (ClassNotFoundException ex)
{
System.out.println(ex);
}
catch (IOException ex)
{
System.out.println(ex);
}
}

Brain power By 2020, wind could provide one-tenth of our planets


electricity needs. Already today, SKFs innovative know-
how is crucial to running a large proportion of the
worlds wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

54
54
JAVA 5: FILES AND JAVA IO java.Io
java.io

However, it is rare that you do that. If you have multiple objects and as here an array of
objects (or an ArrayList of objects), you will usually serialize it all but as a single operation:

private static void test11()


{
try (ObjectOutputStream stream =
new ObjectOutputStream(new FileOutputStream("personer")))
{
Person[] pers = {
new Person("Carlo Jensen", new GregorianCalendar(1949, 0, 23), 225),
new Person("Gudrun Andersen", new GregorianCalendar(1963, 10, 3), 325),
new Person("Abelone Srensen", new GregorianCalendar(1972, 3, 13), 375) };
stream.writeObject(pers);
}
catch (IOException ex)
{
System.out.println(ex);
}
try (ObjectInputStream stream =
new ObjectInputStream(new FileInputStream("personer")))
{
Person[] pers = (Person[])stream.readObject();
for (Person p : pers) System.out.println(p);
}
catch (ClassNotFoundException ex)
{
System.out.println(ex);
}
catch (IOException ex)
{
System.out.println(ex);
}
}

It is possible, as the class Array is Serializable. The same applies to the collection classes,
and therefore they can also be serialized.

SERIALIZES AN OBJECT HIERARCHY

The following class inherits Person and expands the class Person with a job title

class Employee extends Person


{
private String job;

55
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io
JAVA 5: FILES AND JAVA IO java.Io

public Employee(String name, String job, Calendar fdate, double sats)


public Employee(String name, String job, Calendar fdate, double sats)
{
{
super(name, fdate, sats);
super(name, fdate, sats);
this.job = job;
this.job = job;
}
}

public String toString()


public String toString()
{
{
return job + "\n" + super.toString();
return job + "\n" + super.toString();
}
}
}
}

You should
You should note
note that
that the
the class
class is
is not
not defined
defined Serializable,
Serializable, but
but objects
objects of
of this
this type
type can
can still
still
You should note that the class is not defined Serializable, but objects of this type can still
be serialized
be serialized because
because the
the base
base class
class is
is Serializable:
Serializable:
be serialized because the base class is Serializable:

private static void test12()


private static void test12()
{
{
try (ObjectOutputStream stream =
try (ObjectOutputStream stream =
new ObjectOutputStream(new FileOutputStream("employee")))
new ObjectOutputStream(new FileOutputStream("employee")))
{
{
Employee e = new Employee("Carlo Jensen", "Executioner",
Employee e = new Employee("Carlo Jensen", "Executioner",
new GregorianCalendar(1949, 0, 23), 225);
new GregorianCalendar(1949, 0, 23), 225);
stream.writeObject(e);
stream.writeObject(e);
}
}
catch (IOException ex)
catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
try (ObjectInputStream stream =
try (ObjectInputStream stream =
new ObjectInputStream(new FileInputStream("employee")))
new ObjectInputStream(new FileInputStream("employee")))
{
{
Employee e = (Employee)stream.readObject();
Employee e = (Employee)stream.readObject();
System.out.println(e);
System.out.println(e);
}
}
catch (ClassNotFoundException ex)
catch (ClassNotFoundException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
catch (IOException ex)
catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

That
That is,
is, it
it works
works because
because an
an Employee
Employee is
is Serializable
Serializable as
as it
it inherits
inherits aaa Serializable
Serializable class.
class.
That is, it works because an Employee is Serializable as it inherits Serializable class.

56
56
56
JAVA
JAVA5:
5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.io
java.Io

USER
USERDEFINED
DEFINEDWRITEOBJECT()
WRITEOBJECT()AND
ANDREADOBJECT()
READOBJECT()
Sometimes
Sometimes you you want
want to to determine
determine byby yourself
yourself how
how thethe objects
objects must
must be
be serialized
serialized andand
deserialized
deserialized and and depart
depart from
from the
the default
default operations.
operations. AA typical
typical reason
reason could
could be
be performance,
performance,
but
butthere
therecould
couldalsoalsobebeother
otherreasons.
reasons.The
Theprocess
processisisquite
quitesimple,
simple,since
sincethe
theclass
classititisisdesired
desired
to
to serialize
serialize asas usual
usual must
must bebe defined
defined Serializable
Serializable and
and in
in addition
addition implements
implements the the methods
methods
writeObject()
writeObject() and and the
the readObject().
readObject(). Then
Then these
these methods
methods are are used
used instead
instead of
of the
the default
default
methods
methods in in ObjectOutputStream
ObjectOutputStream and and ObjectInputStream.
ObjectInputStream. The The following
following class
class implements
implements
these
these methods:
methods:

class Name implements Serializable


{
private String name;
private Calendar time = null;

public Name(String name)


{
this.name = name;
}

57
57
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io
JAVA 5: FILES AND JAVA IO java.Io

private void
void writeObject(ObjectOutputStream
writeObject(ObjectOutputStream out)
out) throws
throws IOException
IOException
private
{{
out.writeUTF(name);
out.writeUTF(name);
}}

private void
void readObject(ObjectInputStream
readObject(ObjectInputStream in)
in)
private
throws ClassNotFoundException, IOException
throws ClassNotFoundException, IOException
{
{
name == in.readUTF();
in.readUTF();
name
time == Calendar.getInstance();
Calendar.getInstance();
time
}
}
public String
String toString()
toString()
public
{
{
return name
name ++ "\n"
"\n" ++ (time
(time ==
== null
null ?? "Not
"Not desirialized"
desirialized" :: getTime());
getTime());
return
}
}

private String getTime()


private String getTime()
{
{
return
return
String.format("%02d-%02d-%04d %02d:%02d:%02d:%03d",
%02d:%02d:%02d:%03d", time.get(Calendar.DATE),
time.get(Calendar.DATE),
String.format("%02d-%02d-%04d
time.get(Calendar.MONTH) + 1, time.get(Calendar.YEAR),
time.get(Calendar.MONTH) + 1, time.get(Calendar.YEAR),
time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE),
time.get(Calendar.MINUTE),
time.get(Calendar.HOUR_OF_DAY),
time.get(Calendar.SECOND), time.get(Calendar.MILLISECOND));
time.get(Calendar.SECOND), time.get(Calendar.MILLISECOND));
}
}
}
}

When
When an
an object
object is
is serialized,
serialized, only
only the
the field
field name
name will
will be
be saved
saved while
while the
the date
date first
first is
is created
created
When an object is serialized, only the field name will be saved while the date first is created
when
when the
the object
object is
is deserialized
deserialized and
and thus
thus shows
shows when
when the
the object
object is
is deserialized:
deserialized:
when the object is deserialized and thus shows when the object is deserialized:

private static void test13()


private static void test13()
{{
try (ObjectOutputStream
(ObjectOutputStream stream
stream ==
try
new ObjectOutputStream(new FileOutputStream("name")))
new ObjectOutputStream(new FileOutputStream("name")))
{{
Name name
name == new
new Name("Carlo
Name("Carlo Jensen");
Jensen");
Name
stream.writeObject(name);
stream.writeObject(name);
System.out.println(name);
System.out.println(name);
}}
catch (IOException
(IOException ex)
ex)
catch
{{
System.out.println(ex);
System.out.println(ex);
}}
try (ObjectInputStream
(ObjectInputStream stream
stream ==
try
new ObjectInputStream(new
new ObjectInputStream(new FileInputStream("name")))
FileInputStream("name")))
{
{
Name name
name == (Name)stream.readObject();
(Name)stream.readObject();
Name
System.out.println(name);
System.out.println(name);
}}

58
58
58
JAVA 5: FILES AND JAVA IO java.io
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.Io
java.Io

catch
catch (ClassNotFoundException
(ClassNotFoundException ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
catch (IOException
catch (IOException ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

Carlo
Carlo Jensen
Jensen
Not desirialized
Not desirialized
Carlo
Carlo Jensen
Jensen
26-12-2016
26-12-2016 12:14:51:792
12:14:51:792

You
Youshould
You shouldnote
should notethat
note thatthe
that theserialization
the serializationand
serialization anddeserialization
and deserializationsyntactically
deserialization syntacticallyhappens
syntactically happensinin
happens inexactly
exactly
exactly
the
thesame
the sameway.
same way.Its
way. Itsjust
Its just some
just some other
some other methods
other methods that
methods that are
that are performed.
are performed.
performed.

EXTERNALIZABLE
EXTERNALIZABLE
EXTERNALIZABLE
ItIt
It isis
is also
also possible
also possible completely
possible completely self
completely self toto
self to address
address how
address how the
how the objects
the objects should
objects should be
should be serialized
be serialized and
serialized and
and
deserialized,
deserialized, and
and again
again could
could performance
performance bebe a areason.
reason.The
Theclass
class that
thatshould
should
deserialized, and again could performance be a reason. The class that should be serialized be
be serialized
serialized
must
must instead
must instead ofof
instead of Serializable
Serializable implement
Serializable implement the
implement the interface
the interface Externalizable,
interface Externalizable, which
Externalizable, which defines
which defines two
defines two
two
methods
methods writeExternal()
methods writeExternal() and
writeExternal() and readExternal():
and readExternal():
readExternal():

class
class King
King implements
implements Externalizable
Externalizable
{
{
private
private String
String name;
name;
private int from;
private int from;
private
private int
int to;
to;

public
public King()
King()
{
{
}
}

public
public King(String
King(String name,
name, int
int from,
from, int
int to)
to)
{
{
this.name
this.name =
= name;
name;
this.from
this.from = from;
= from;
this.to
this.to =
= to;
to;
}
}

59
59
59
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

public String toString()


{
if (from == Integer.MIN_VALUE && to == Integer.MIN_VALUE) return name;
if (to == Integer.MIN_VALUE) return name + String.format(" : %d -", from);
if (from == Integer.MIN_VALUE) return name + String.format(" : %d", to);
return name + String.format(" : %d %d", from, to);
}
public void writeExternal(ObjectOutput out) throws IOException
{
out.writeUTF(name);
out.writeInt(from);
out.writeInt(to);
}

public void readExternal(ObjectInput in)


throws IOException, ClassNotFoundException
{
name = in.readUTF();
from = in.readInt();
to = in.readInt();
}
}

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

60
60
JAVA
JAVA5:
5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.io
java.Io

These
These methods
methods must
must thenthen respectively
respectively write
write to
to an
an ObjectOutput
ObjectOutput and and reading
reading from
from an an
ObjectInput,
ObjectInput, there
there are
are the
the interfaces,
interfaces, as
as are
are implemented
implemented byby an
an ObjectOutputStream
ObjectOutputStream and and an
an
ObjectInputStream.
ObjectInputStream. The The syntax
syntax for
for serialization
serialization and
and deserialization
deserialization of
of an
an object
object isis in
in turn
turn
the
the same
same as
as before:
before:

private static void test14()


{
try (ObjectOutputStream stream =
new ObjectOutputStream(new FileOutputStream("king")))
{
King king = new King("Knud den Hellige", 1080, 1086);
stream.writeObject(king);
}
catch (IOException ex)
{
System.out.println(ex);
}
try (ObjectInputStream stream =
new ObjectInputStream(new FileInputStream("king")))
{
King king = (King)stream.readObject();
System.out.println(king);
}
catch (ClassNotFoundException ex)
{
System.out.println(ex);
}
catch (IOException ex)
{
System.out.println(ex);
}
}

61
61
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.io
java.Io

2.5
2.5 CHARACTER
CHARACTERSTREAMS
STREAMS
There
Therealsoalsoisisaafamily
familyofofclasses
classesthat
thatare
areused
usedtotostream
streamaasequence
sequenceofofcharacters
charactersandandthus
thusaa
text.
text.InInfact,
fact,they
theyare
arefar
farmore
moreoftenoftenneeded
neededthanthandirectly
directlystream
streamaasequence
sequenceofofbytes
bytes(and
(and
hence
hencethe therawrawdata).
data).InInJava
Javaisistext
textororcharacters
charactersrepresented
representedasas22bytes
bytesunicodes,
unicodes,but butwhen
when
they
theyarearestreamed
streamedtotoaafile,
file,aacharacter
characterfill
fillone
oneororaafew
fewbytes
bytesasastext
textisisencoded
encodedasasUTF8.
UTF8.
All
Allthe
theregular
regularletters
lettersoccupies
occupiesonly onlyone
onebyte,
byte,while
whileothers
othersthat
thatare
arenot
notsosofrequently
frequentlyusedused
characters,
characters,including
includingnational
nationalcharacters
charactersoccupies
occupies22orormoremorebytes.
bytes.The
Thegoal
goalisissimple
simpletoto
reduce
reducethe thenumber
numberofofbytes
bytessent
sentover
overaastream.
stream.Stream
Streamclasses
classestotocharacters
charactersmust
musthandle
handlethe the
necessary
necessaryconversion
conversionthatthathappens
happenstransparently
transparentlywithout
withoutthetheprogrammers
programmersinvolvement
involvementatat
least
leastasaslong
longthat
thatthe
theprogram
programshould
shouldnot notbebeused
usedanywhere
anywhereininthisthisworld.
world.Strictly
Strictlyspeaking,
speaking,
not
notthethesame
sameencoding
encodingare areused
usedeverywhere
everywherebut butthe
theentire
entireWestern
Westernworld
worldusesusesthethesame
same
encoding.
encoding.IfIfyou youneed
needinternationalization,
internationalization,ititisispossible
possibletotospecify
specifythe
theencoding
encodingtotobe beused,
used,
but
butotherwise
otherwisestream
streamclasses
classesuses
usesan anencoding
encodingbased
basedon onthe
themachines
machineslocal
localsetting.
setting.Below
Below
isisan
anexample
examplethat thatwrites
writestext
texttotoaafile
fileand
andread
readthe
thetext
textagain:
again:

private static void test15()


{
try (FileWriter writer = new FileWriter("names"))
{
writer.write("Gorm den Gamle\n");
writer.write("Harald Bltand\n");
writer.write("Svend Tveskg\n");
}
catch (IOException ex)
{
System.out.println(ex);
}
char[] buffer = new char[20];
try (FileReader reader = new FileReader("names"))
{
for (int count = reader.read(buffer, 0, buffer.length); count != -1;
count = reader.read(buffer, 0, buffer.length))
for (int i = 0; i < count; ++i) System.out.print(buffer[i]);
}
catch (IOException ex)
{
System.out.println(ex);
}
}

6262
JAVA 5:
JAVA 5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.Io
java.io

The methods
The methods writes
writes strings
strings separated
separated by
by line
line breaks,
breaks, and
and the
the text
text are
are loaded
loaded again
again in
in aa
buffer whose
buffer whose content
content then
then are
are printed
printed on
on the
the screen.
screen. When
When you
you in
in this
this way
way wants
wants to to deal
deal
with text
with text files,
files, you
you will
will usually
usually encapsulate
encapsulate both
both the
the writer
writer and
and the
the reader
reader in
in aa buffer,
buffer, and
and
here you
here you should
should especially
especially notice
notice how
how to
to read
read files
files with
with the
the method
method readLine()
readLine() and
and thus
thus
perceive the
perceive the file
file as
as line-oriented:
line-oriented:

private static void test16()


{
try (BufferedWriter writer = new BufferedWriter(new FileWriter("names")))
{
writer.write("Gorm den Gamle");
writer.newLine();
writer.write("Harald Bltand");
writer.newLine();
writer.write("Svend Tveskg");
}
catch (IOException ex)
{
System.out.println(ex);
}
try (BufferedReader reader = new BufferedReader(new FileReader("names")))
{

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

63
63
JAVA 5: FILES AND JAVA IO java.io
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.Io
java.Io

for
for (String
(String line
line == reader.readLine();
reader.readLine(); line
line !=
!= null;
null; line
line == reader.readLine())
reader.readLine())
System.out.println(line);
System.out.println(line);
}}
catch
catch (IOException
(IOException ex)
ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
}}

In the
In the
In above
the above example
example III used
above example used
used aaa FileWriter
FileWriter and
FileWriter and FileReader
and FileReader as
FileReader as character-oriented
as character-oriented stream
character-oriented stream classes
stream classes
classes
to files
to files
to and
files and including
and including BufferedWriter
including BufferedWriter and
BufferedWriter and BufferedReader,
and BufferedReader, but
BufferedReader, but there
but there are
there are other
are other Reader
other Reader and
Reader and
and
Writer classes,
Writer classes,
Writer there
classes, there most
there most
most bebe important:
be important:
important:

---- FileReader
FileReader FileWriter
FileWriter
FileReader FileWriter
---- FilterReader
FilterReader FilterWriter
FilterWriter
FilterReader FilterWriter
---- StringReader
StringReader StringWriter
StringWriter
StringReader StringWriter
---- PipedReader
PipedReader PipeWriter
PipeWriter
PipedReader PipeWriter
---- CharArrayReader
CharArrayReader CharArrayWriter
CharArrayWriter
CharArrayReader CharArrayWriter
---- InputStreamReader
InputStreamReader OutputStreamWriter
OutputStreamWriter
InputStreamReader OutputStreamWriter
---- PrintWriter
PrintWriter
PrintWriter

You should
You should
You also
should also note
also note that
that aaa FileReader
note that FileReader and
FileReader and FileWriter
and FileWriter isis wrapper
FileWriter is wrapper classes
wrapper classes for
classes for respectively
for respectively an
respectively an
an
InputStreamReader and
InputStreamReader and
InputStreamReader an
and an OutputStreamWriter.
an OutputStreamWriter.
OutputStreamWriter.

Sometimes
Sometimes it
Sometimes itit is
isis recommended
recommended not
recommended not to
not to use
to use the
use the FileReader
the FileReader and
FileReader and FileWriter,
and FileWriter, as
FileWriter, as they
as they do
they do not
do not allow
not allow
allow
you to
you to
you enter
to enter
enter anyany Encoding.
any Encoding. The
Encoding. The same
The same method
same method
method asas above
as above can
above can be
can be written
be written as
written as follows
as follows where
follows where you
where you
you
indicates the
indicates the
indicates encoding:
the encoding:
encoding:

private
private static
static void
void test17()
test17()
{{
try
try (BufferedWriter
(BufferedWriter writer
writer == new
new BufferedWriter(
BufferedWriter(
new
new OutputStreamWriter(new FileOutputStream("navne2"), "ISO-8859-1")))
OutputStreamWriter(new FileOutputStream("navne2"), "ISO-8859-1")))
{{
writer.write("Gorm
writer.write("Gorm den
den Gamle");
Gamle");
writer.newLine();
writer.newLine();
writer.write("Harald
writer.write("Harald Bltand");
Bltand");
writer.newLine();
writer.newLine();
writer.write("Svend
writer.write("Svend Tveskg");
Tveskg");
}}
catch
catch (IOException
(IOException ex)
ex)
{{
System.out.println(ex);
System.out.println(ex);
}}

64
64
64
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.io
java.Io
JAVA 5: FILES AND JAVA IO java.Io

try (BufferedReader reader =


try (BufferedReader reader =
new BufferedReader(new InputStreamReader(
new BufferedReader(new InputStreamReader(
new FileInputStream("navne2"), "ISO-8859-1")))
new FileInputStream("navne2"), "ISO-8859-1")))
{
{
for (String line = reader.readLine(); line != null; line = reader.readLine())
for (String line = reader.readLine(); line != null; line = reader.readLine())
System.out.println(line);
System.out.println(line);
}
}
catch (IOException ex)
catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

In this
In this case,
case, indicates
indicates thethe encoding
encoding that
that itit not
not should
should be
be UTF8
UTF8 butbut ISO
ISO 8859-1,
8859-1, in in which
which
In this case, indicates the encoding that it not should be UTF8 but ISO 8859-1, in which
all characters
all characters areare encoded
encoded as as aa single
single byte.
byte. TheThe main
main use
use of
of this
this option
option isis that
that you
you may
may
all characters are encoded as a single byte. The main use of this option is that you may
need to
need to read
read text
text files
files created
created with
with another
another program
program and
and then
then not
not may
may be
be UTF8
UTF8 encoded.
encoded.
need to read text files created with another program and then not may be UTF8 encoded.

PROBLEM 22
PROBLEM
PROBLEM 2
The folder
The folder to
to this
this book
book contains
contains three
three text
text files
files called
called
The folder to this book contains three text files called

1. regions,
1. regions, that
that contains
contains aa line
line for
for each
each Danish
Danish region
region where
where aa line
line consists
consists of
of aa region
region
1. regions, that contains a line for each Danish region where a line consists of a region
number and
number and the
the name
name of of the
the region
region separated
separated by by commas
commas
number and the name of the region separated by commas
2. municipalities,
2. municipalities, that
that contains
contains aa line
line for
for each
each Danish
Danish municipality,
municipality, where
where thethe line
line
2. municipalities, that contains a line for each Danish municipality, where the line
consists of
consists of the
the municipalitys
municipalitys number,
number, the the name
name ogog the
the municipality
municipality and and thethe
consists of the municipalitys number, the name og the municipality and the
number of
number of the
the region
region that
that the
the municipality
municipality belongs
belongs and
and where
where the
the three
three fields
fields are
are
number of the region that the municipality belongs and where the three fields are
separated by
separated by commas
commas
separated by commas
3. zipcodes,
3. zipcodes, that
that contains
contains aa line
line for
for each
each zip
zip code,
code, where
where thethe line
line consists
consists of
of the
the postal
postal
3. zipcodes, that contains a line for each zip code, where the line consists of the postal
code and
code and the
the city
city name,
name, followed
followed by by one
one oror more
more municipality
municipality numbers
numbers indicating
indicating
code and the city name, followed by one or more municipality numbers indicating
themunicipalities
the municipalitiesthat thatuse
usethis
thiszip
zipcode
codeand
andwhere
whereall
allfields
fieldsare
areseparated
separatedby bycommas
commas
the municipalities that use this zip code and where all fields are separated by commas

You must
You must now
now create
create aa new
new project
project in
in NetBeans,
NetBeans, as
as you
you for
for example
example can
can call
call for
for Denmark.
Denmark.
You must now create a new project in NetBeans, as you for example can call for Denmark.
You must
You must then
then add
add the
the following
following three
three interfaces
interfaces to
to your
your project
project and
and write
write classes
classes that
that
You must then add the following three interfaces to your project and write classes that
implements these
implements these interfaces:
interfaces:
implements these interfaces:
package denmark;
package denmark;
/**
/**
* Interface, thar defines a region.
* Interface, thar defines a region.
* Two regions are equal if they have the same region number.
* Two regions are equal if they have the same region number.
* Regions are ordred ascending after name.
* Regions are ordred ascending after name.
* The iterator pattern must be implemented to iterates this
* The iterator pattern must be implemented to iterates this
* region's municipalities.
* region's municipalities.
*/
*/

65
65
65
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

public interface IRegion extends


Comparable<IRegion>, Iterable<IMunicipality>, java.io.Serializable
{
/**
* @return The region's number
*/
public int getRnr();

/**
* @return The regions name
*/
public String getName();

/**
* @return Number of municipalities in this region
*/
public int getSize();

/**
* Returns the municipality in this region with number mnr
* @param mnr Municipality number
* @return The municipality in this region with number mnr
* @throws Exception If the region not has a municipality with number mnr
*/

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

66
66
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

public IMunicipality getMunicipality(int mnr) throws Exception;

/**
* Change the region's name
* @param name The regions name
*/
public void setName(String name);

/**
* Add a municipality to this region.
* @param municipality The municipality to be added
* @throws Exception If the region already has a municipality with that number
*/
public void addMunicipality(IMunicipality municipality) throws Exception;

/**
* Remove a municipality from this region.
* @param mnr Number of the municipality to be removed
* @return True, if the municipality is removed
*/
public boolean removeMunicipality(int mnr);
}

package denmark;

/**
* Interface, that defines a municipality.
* Two municipalities are considered equal if they have the same
* municipality number.
* Municipalities are ordered ascending by municipality name.
* Iterator mnsteret definerer at man kan iterere over denne kommunes postnumre.
*/
public interface IMunicipality extends
Comparable<IMunicipality>, Iterable<IZipcode>, java.io.Serializable
{
/**
* @return The municipality's number
*/
public int getMnr();

/**
* @return The municipality's name
*/
public String getName();

67
67
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

/**
* @return The region in which this municipality belongs
*/
public IRegion getRegion();

/**
* @return Number of zip codes, as this municipality uses
*/
public int getSize();

/**
* Returns the zip code with the number code if this municipality uses
* this zip code.
* @param code The code of the zip code to be returned
* @return The zip code with the number code if this municipality uses this code.
* @throws Exception If the municipality does not use this code
*/
public IZipcode getZipcode(String code) throws Exception;

/**
* Changes the name of the municipality
* @param name The new name
*/
public void setName(String name);

/**
* Move this municipality in another region.
* @param region The other region
*/
public void setRegion(IRegion region);

/**
* Adds a zip code to this municipality, thus indicating a zip code that
* this municipality uses.
* @param zipcode The zip code that should be added
* @throws Exception If this municipality already uses this code
*/
public void addZipcode(IZipcode zipcode) throws Exception;

/**
* Removing a zip code from this municipality, thus indicating that
* this municipality does not use the code.
* @param code The zip code to be removed
* @return True, if the zip code was removed
*/
public boolean removeZipcode(String code);
}

68

68
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

package denmark;
/**
* Interface, that defines a zip code.
* Two zip codes are considered equal if they have the same number.
* Zip codes are ordered ascending by the code.
* the iterator pattern defines that you can iterates the municipalities, that
* use this zip code.
*/
public interface IZipcode extends
Comparable<IZipcode>, Iterable<IMunicipality>, java.io.Serializable
{
/**
* @return The code
*/
public String getCode();

360
/**
* @return The city

.
*/

thinking
public String getCity();

360
thinking . 360
thinking .
Discover the truth at www.deloitte.ca/careers Dis

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


69
69
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

/**
* @return Number of municipalities that uses this zip code.
*/
public int getSize();

/**
* Returns the municipality with number mnr if the municipality uses
* this zip code.
* @param mnr Municipality number
* @return The municipality with number mnr if the municipality uses this code.
* @throws Exception If the municipality with number mnr uses this zip code
*/
public IMunicipality getMunicipality(int mnr) throws Exception;

/**
* Changed the zip code's city name
* @param city City name
*/
public void setCity(String city);

/**
* Adds a municipality to this Zipcode object and thus indicates that this
* zip code is used by the municipality.
* @param municipality The municipality to be added
* @throws Exception If the municipality already added
*/
public void addMunicipality(IMunicipality municipality) throws Exception;

/**
* Removes the municipality with the number mnr from this zip code and
* thus indicates that the municipality does not use this zip code.
* @param mnr The number of the municipality to be removed
* @return True, if the municipality was removed
*/
public boolean removeMunicipality(int mnr);
}

You must then write the following class, when the class must be written as a singleton:

package denmark;

import java.util.*;
import java.io.*;

70
70
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

public class Repository implements Serializable


{
private static String filename = "denmark"; // filename to serialization the data
private static Repository instance = null; // variable to an instance
private List<IRegion> regions; // to regions
private List<IMunicipality> municipalities; // to municipalities
private List<IZipcode> zipcodes; // to zip codes

public static Repository getInstance()


{
}

/**
* Returns the zip code from the code.
* @param code The code
* @return The zip code if it is found and else null
*/
public IZipcode getZipcode(String code)
{
}

/**
* Returns the region with region number rnr.
* @param rnr Region number
* @return The region if it is found and else null
*/
public IRegion getRegion(int rnr)
{
}

/**
* Returns the municipality with number mnr.
* @param mnr Municipality number
* @return The municipality if it is found and else null
*/
public IMunicipality getMunicipality(int mnr)
{
}

/**
* @return Iterator, that iterates til zip codes.
*/
public Iterator<IZipcode> itrZipcode()
{
}

71
71
JAVA 5: FILES AND JAVA IO java.io
JAVA 5: FILES AND JAVA IO java.Io

/**
* @return Iterator, that iterates til regions.
*/
public Iterator<IRegion> itrRegioner()
{
}

/**
* @return Iterator, that iterates til municipalities.
*/
public Iterator<IMunicipality> itrMunicipality()
{
}

private Repository()
{
}
}

The class is defined Serializable, and the private constructor must start by deserialize an
The class is defined Serializable, and the private constructor must start by deserialize an
object of the type Repository. Is it not possible, the constructor instead must initialize an
object of the type Repository. Is it not possible, the constructor instead must initialize an
object from the contents of the three text files and then serialize the object.
object from the contents of the three text files and then serialize the object.

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

72
72
JAVA 5: FILES AND JAVA IO java.io

The program should open the window, as shown below where it should be possible to
search for regions, municipalities and zip codes. You can enter the following search texts:

1. Region that matches all regions where the name contains the search text
2. Municipality, that matches all municipalities where the name contains with the
search text
3. City that matches all zip codes where the city starts with the search text
4. Zip code that maches all zip codes where the code starts with the search text

It is a part of the task to decide what it will mean if a search is combined of several criteria,
but if, for example you searches municipalities and typed something for municipality and
city, it might for example mean that you should see the names of all the municipalities
where the municipalitys name contains the search text for municipality and the municipality
uses the zip code that matches the search text for city name.

73
JAVA 5:
JAVA 5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.Io
java.io

2.6 TEXT SCANNER


2.6
During data
During data entry
entry for
for console
console applications
applications II have
have used
used the
the class
class Scanner,
Scanner, and
and itit can
can be
be used
used
for anything
for anything other
other than
than simply
simply entering
entering data.
data. Basicly
Basicly aa Scanner
Scanner isis an
an object
object that
that scans
scans aa
character-oriented stream
character-oriented stream and
and divides
divides the
the stream
stream into
into tokens.
tokens. Consider
Consider as
as an
an example
example the
the
following method:
following method:

private static void test18()


{
try (BufferedWriter writer = new BufferedWriter(new FileWriter("names")))
{
writer.write("Gorm den Gamle");
writer.newLine();
writer.write("Harald Bltand");
writer.newLine();
writer.write("Svend Tveskg");
}
catch (IOException ex)
{
System.out.println(ex);
}
try (Scanner scan = new Scanner(new BufferedReader(new FileReader("names"))))
{
// scan.useDelimiter("\n");
while (scan.hasNext()) System.out.println(scan.next());
}
catch (IOException ex)
{
System.out.println(ex);
}
}

The method
The method starts
starts by
by creating
creating aa text
text file
file called
called names.
names. Then
Then the
the method
method writes
writes three
three lines
lines to
to
the file,
the file, as
as are
are names
names of of three
three Danish
Danish kings.
kings. The
The last
last part
part of
of the
the method
method creates
creates aa scanner,
scanner,
which scans
which scans the
the file
file names
names and
and then
then prints
prints the
the tokens,
tokens, that
that is
is determined,
determined, with
with one
one token
token
at each
at each line.
line. The
The result
result is:
is:

Gorm
den
Gamle
Harald
Bltand
Svend
Tveskg

74
74
JAVA 5: FILES AND JAVA IO java.Io
JAVA 5: FILES AND JAVA IO java.io
java.Io

By default
By default tokens
tokens areare separated
separated byby aa white
white spaces,
spaces, which
which are
are space,
space, tab
tab and
and newline.
newline.
Therefore, the
Therefore, the file
file names
names has
has 77 tokens.
tokens. If
If you
you wish,
wish, you
you can
can specify
specify how
how the
the tokens
tokens must
must
be separated,
be separated, and
and itit you
you remove
remove the
the comment
comment in in the
the above
above method,
method, only
only line
line breaks
breaks are
are
used to
used to separates
separates tokens,
tokens, and
and the
the result
result is:
is:

Gorm den Gamle


Gorm den Gamle
Harald Bltand
Harald Bltand
Svend Tveskg
Svend Tveskg

The parameter
The parameter to
to the
the method
method useDelimiter()
useDelimiter() is
is aaa string
string that
that can
can be
be any
any regular
regular expression,
expression,
The parameter to the method useDelimiter() is string that can be any regular expression,
and you
and you is
is thus
thus able
able to
to provide
provide very
very complex
complex patterns
patterns for
for seperation
seperation of
of tokens.
tokens.
and you is thus able to provide very complex patterns for seperation of tokens.

The class
class Scanner
Scanner also
also has
has methods
methods that
that can
can convert
convert tokens
tokens to
to the
the primitive
primitive types
types
if
ifif the
The the
The class Scanner also has methods that can convert tokens to the primitive types the
tokens has
tokens has legal
legal values.
values. Otherwise
Otherwise the
the conversion
conversion throws
throws an
an exception.
exception. Consider
Consider asas an an
tokens has legal values. Otherwise the conversion throws an exception. Consider as an
example the
example the following
following method:
method:
example the following method:

private static void test19()


private static void test19()
{
{
try (BufferedWriter writer = new BufferedWriter(new FileWriter("numbers")))
try (BufferedWriter writer = new BufferedWriter(new FileWriter("numbers")))
{
{
Random rand = new Random();
Random rand = new Random();

e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili www.discovermitas.com
Maersk.com/Mitas e G
I joined MITAS because for Engine
I wanted real responsibili Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
ree wo
work
or placements ssolve pr

75
75
75
JAVA 5: FILES AND JAVA IO java.io
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO java.Io
IO java.Io

for
for (int
(int ii == 0;
0; ii << 10;
10; ++i)
++i)
writer.write(String.format("%d
writer.write(String.format("%d %1.2f\n",
%1.2f\n",
rand.nextInt(10)
rand.nextInt(10) ++ 1, 1, rand.nextDouble()
rand.nextDouble() ** 100));
100));
}}
catch
catch (IOException
(IOException ex)ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
try
try (Scanner
(Scanner scan
scan == new
new Scanner(new
Scanner(new BufferedReader(new
BufferedReader(new FileReader("numbers"))))
FileReader("numbers"))))
{{
double
double sum
sum == 0;
0;
while
while (scan.hasNext()) sum
(scan.hasNext()) sum +=
+= scan.nextInt()
scan.nextInt() ** scan.nextDouble();
scan.nextDouble();
System.out.println(sum);
System.out.println(sum);
}}
catch
catch (IOException
(IOException ex)ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
}}

The
The method
method prints
prints 10
10 lines
lines to
to aa file
file in
in which
which each
each line
line contains
contains anan integer
integer and
and aa decimal
decimal
number separated by a space. Next, the file is scanned, but as part of the scan
number separated by a space. Next, the file is scanned, but as part of the scan the elements the elements
are
are converted
converted (the
(the individual
individual tokens)
tokens) to to either
either anan int
int or
or aa double
double and
and the
the product
product isis calculated.
calculated.

EXERCISE
EXERCISE 55
AA common
common use use of of text
text files
files isis to
to transfer
transfer data
data between
between applications.
applications. An
An application
application can
can store
store
information
information in a text file that can be sent to a recipient who then read the content of the
in a text file that can be sent to a recipient who then read the content of the
file. Often that kind of files are called CSV files. CSV stands for
file. Often that kind of files are called CSV files. CSV stands for comma separated values, comma separated values,
noting
noting that that the
the file
file contains
contains valuesvalues thatthat are
are separated
separated byby aa comma.
comma. The
The separation
separation character
character
do
do not not necessarily
necessarily needsneeds to to bebe aa comma
comma and and can
can bebe anything.
anything. The
The only
only requirement
requirement isis that
that
itit isis aa character that can not occur in the individual data elements (values).
character that can not occur in the individual data elements (values). Besides comma Besides comma
are
are often used
often used spaces,
spaces, semicolons,
semicolons, tabulator,
tabulator, oror equivalent,
equivalent, but
but whatever
whatever character
character you
you use
use
the file is still called a CSV file. In this exercise you have to write
the file is still called a CSV file. In this exercise you have to write a program that creates a program that creates
aa CSV
CSV file file and
and read
read itit again.
again.

Create
Create aa new
new project,
project, you
you can
can call
call CsvFiles.
CsvFiles. Add Add aa method
method that
that creates
creates aa text
text file
file which
which
consists of lines that start with a date and is followed by one or more decimal
consists of lines that start with a date and is followed by one or more decimal numbers numbers
separated
separated by
by semicolons.
semicolons. The
The start
start of
of the
the file
file could,
could, for
for example
example be:
be:

17.04.2014;573,33;228,97;242,14;394,81;190,60;412,17;107,02;249,49;293,29
17.04.2014;573,33;228,97;242,14;394,81;190,60;412,17;107,02;249,49;293,29
11.09.2012;325,04;87,59;325,25;465,42
11.09.2012;325,04;87,59;325,25;465,42
31.12.2013;992,33;695,32
31.12.2013;992,33;695,32

76
76
76
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.io
java.Io

AAline
linecould,
could,for
forexample
examplebe beinterpreted
interpretedasasaanumber
numberofofamounts
amounts(for
(forexample
exampleproduct
product
sales)
sales) as concerning a certain date. You should note, that there can be several lines withthe
as concerning a certain date. You should note, that there can be several lines with the
same date and in any order. The difficult thing is not to create the file, but to creates
same date and in any order. The difficult thing is not to create the file, but to creates the the
lines
linestotobe
beprinted
printedtotothe
thefile,
file,sosoyou
youshould
shouldcreate
createsome
somehelper
helpermethods.
methods.

You
Youmust
mustthen
thenwrite
writeaamethod
methodthat
thatreads
readsthe
thecontent
contentofofthe
thefile,
file,and
andprints
printsaalist
listasasshown
shown
below:
below:

02.01.2012: 1848,44
04.01.2012: 3303,82
05.01.2012: 756,04
08.01.2012: 9773,91

Thetable
The tablemust
mustshow
showthe
thetotal
totalsales
salesfor
foreach
eachdate,
date,and
andthe
thelines
linesmust
mustbe
besorted
sortedby
bydate.
date.

CSVfiles
CSV filesare
aretypically
typicallyline
lineoriented,
oriented,but butititneed
neednotnotbe
bethe
thecase.
case.You
Youhave
havetotowrite
writeanother
another
methodthat
method thatcreates
createsaatext
textfile,
file,but
butthe
thefile
filemust
mustconsist
consistofofelements
elementsseparated
separatedby bysemikolen
semikolen
whichisisalternately
which alternatelyaadate
dateand
andaanumber.
number.Next,Next,write
writeaamethod
methodthatthatreads
readsthe
thefile
fileand
andprints
prints
anoverview
an overviewasasabove.
above.Because
Becausethe thefile
fileisisnot
notline
lineoriented,
oriented,ititmust
mustbeberead
readininaadifferent
different
way,and
way, andthis
thiscan
canadvantageously
advantageouslybe bedone
doneby byuse
useofofaascanner.
scanner.

77
77
JAVA 5: FILES AND JAVA IO java.nio

3 JAVA.NIO
The above defines in principle what is necessary in order to work with files, but modern
operating systems provide many services available that are not supported by the classes in
java.io, and it is the reason for another package called java.nio. Another reason for a new
package for io is also providing better services available to stream data over a network. In
this book I will only look at the new package for files, but in the book about network
programming, I treat other services that java.nio provides. This chapter describes the main
classes in this package. Basically it is about classes to

-- buffers
-- chanels
-- paths

78
JAVA 5: FILES AND JAVA IO java.nio

The fundamental concept in the new APIs are buffers. A process as JVM performs IO by
asking the operating system to drain the content of a buffer with a write operation, and
accordingly, the JVM ask the operating system to fill a buffer with a read operation. If the
JVM for instance ask the operating system to read from a disk file, the operating system
will send a command to the disk controller to read a block of bytes from the disk and save
them in an operating system buffer. After this operation is completed, the operating system
copies the content of the buffer to a second buffer in the address space of the specified
process as a parameter of the JVM in the read() operation. One of the goals with java.
nio is to increase the efficiency of the necessary copying of data between buffers, and it is
not simple, particularly because the disk controller always reads/writes with a fixed block
size, while the JVM uses variable sized blocks and even blocks, which are not necessarily
contiguous allocated and can be moved by the garbage collector.

One can think of a channel as a conduit used by the operating system to drain or fill a buffer
with bytes from a device such as a disk controller. An example is a FileChannel, and as its
name suggests it acts as a channel between a program and a disk file. It supports several
things that are not possible with standard IO, and here include a locking mechanisms and
memory mapped files.

Finally are paths java.nios representation of the file system.

The following describes the most important classes in the package java.nio, and it is primarily
using simple test methods in the program NioProgram.

3.1 BUFFERS
A buffer is an object that can contain a fixed amount of data that can be sent to or received
from an IO-service, and one can think of a buffer as an object that sits between a program
and a channel. The buffer has basically four characteristics:

1. capacity, that defines how many data elements a Buffer can contain
2. limit, that is a 0-based index, that denotes the first element, that can not be written
or read
3. position, that is a 0-based index, that denotes the position for the next read or write
4. mark, that is a 0-based index, that is used to reset the position

Buffer is an abstract class that provides a number of methods available, but there are concrete
classes for each of the primitive data types, and basically a buffer is an encapsulation of
an array.

79
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo

You
You can
can think
think of
of aa new
new created
created buffer
buffer as
as illustrated
illustrated in
in the
the following
following figure:
figure:

The
The buffer
buffer has
has aa capacity
capacity of
of 10,
10, and
and thethe limit
limit has
has always
always the
the same
same value
value asas capacity
capacity and
and
thus
thus the
the value
value 10.
10. The
The position
position isis initially
initially 0,
0, indicating
indicating the
the element
element in in the
the buffer,
buffer, which
which
can
can be
be accessed.
accessed. position
position will
will always
always havehave aa value
value between
between 00 and
and limit.
limit. The
The pointer
pointer mark
mark isis
initially
initially undefined.
undefined. As As an
an example
example isis shown
shown aa method
method that
that creates
creates aa buffer
buffer ofof bytes,
bytes, which
which
has
has space
space for
for 10
10 elements:
elements:

private static void test01()


{
Buffer buffer = ByteBuffer.allocate(10);
print(buffer);
buffer.limit(8);
buffer.position(3);
print(buffer);
buffer.flip();
print(buffer);
buffer.mark();
buffer.position(2);
print(buffer);
buffer.reset();
print(buffer);
buffer.limit(8);
buffer.position(3);
print(buffer);
buffer.rewind();
print(buffer);
buffer.clear();
print(buffer);
buffer = LongBuffer.allocate(10);
print(buffer);
}

80
80
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

private static Buffer print(Buffer buffer)


private static Buffer print(Buffer buffer)
{
{
System.out.println("Capacitet: " + buffer.capacity());
System.out.println("Capacitet: " + buffer.capacity());
System.out.println("Limit: " + buffer.limit());
System.out.println("Limit: " + buffer.limit());
System.out.println("Position: " + buffer.position());
System.out.println("Position: " + buffer.position());
System.out.println("Remaining: " + buffer.remaining());
System.out.println("Remaining: " + buffer.remaining());
System.out.println(buffer);
System.out.println(buffer);
System.out.println();
System.out.println();
return buffer;
return buffer;
}
}

The
The first
The first statement
first statement creates
statement creates the
creates the buffer
the buffer and
buffer and when
and when the
when the method
the method isis
method is performed
performed isis
performed is the
the result
the result of
result of
of
the
the first
first print
print statement:
statement:
the first print statement:

Capacitet: 10
Capacitet: 10
Limit: 10
Limit: 10
Position: 0
Position: 0
Remaining: 10
Remaining: 10
java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]
java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]

BUSINESS HAPPENS HERE.


www.fuqua.duke.edu/globalmba

81
81
81
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.nio
java.nIo
JAVA 5: FILES AND JAVA IO java.nIo
JAVA 5: FILES AND JAVA IO java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

Here
Here you
you can
can see
see that
that limit
limit from
from start
start isis set
set to
to capacity,
capacity, and
and the
the position
position isis 0.0. You
You can
can also
also
Here you can see that limit from start is set to capacity, and the position is 0. You can also
Here
see
see you
that
that thecan
the see
buffer
buffer that
has
has limit
10
10 from
places
places start
available.is
available. set
Nextto
Next capacity,
limit
limit is
is and
set
set tothe
to 88 position
and
and is
position
position 0. toYou
to 33 can
and
and also
the
the
Here
see you
that can
the see
buffer that
has limit
10 from
places start is
available. set to
Next capacity,
limit is and
set the
to 8 position
and is
position 0. You
to 3 can
and also
the
see
secondthat
second the
print
print buffer
statementhas
statement 10 places
prints
prints the
theavailable.
result
result Next limit is set to 8 and position to 3 and the
see that
second the
print buffer has
statement 10 places
prints theavailable.
result Next limit is set to 8 and position to 3 and the
second print statement prints the result
second print statement prints the result
Capacitet: 10
Capacitet: 10
Capacitet:
Limit: 10
8
Capacitet: 10
Limit: 8
Limit:
Position: 38
Limit:
Position: 38
Position:
Remaining: 3
Position: 5
Remaining: 3
5
Remaining: 5
java.nio.HeapByteBuffer[pos=3 lim=8 cap=10]
Remaining: 5
java.nio.HeapByteBuffer[pos=3 lim=8 cap=10]
java.nio.HeapByteBuffer[pos=3 lim=8 cap=10]
java.nio.HeapByteBuffer[pos=3 lim=8 cap=10]
You
You
You must
must
must specifically
specifically
specifically note
note
note that
that
that there
there
there are
are
are now
now
now 55
5 places
places
places available,
available,
available, and
and
and thus
thus
thus only
only
only access
access
access to
to
to
You must
elements specifically
with an index note
less that
than there
limit are
(the now 5
elements places
with available,
index 3, and
4, 5, thus
6 andonly
7). access
The to
next
You must
elements
elements specifically
with
with an
an index
index note
less
less that
than
than there
limit
limit are
(the
(the now 5
elements
elements places
with
with available,
index
index and thus
3,3,4,4,5,5,66and
andonly
7).
7). access
The
The nextto
next
elements
statement with an
performs index less than limit (the elements with index 3, 4, 5, 6 and 7). The next
elements with
statement
statement performs
performs aaaflip(),
an index flip(),
flip(), which
lesswhich
which means
than limit
means
means(thethat
that
that limit
elements
limit
limit isis
is set
with
set
set to
to
to position,
index
position,
position, while
3, 4,while
while position
5, 6 and
position
position isis
7). Theis set
set
set to
next
to
to
statement
0 (and a performs
possible marka flip(),
to which
undefined).meansThe that limit
result of is
theset to
thirdposition,
print while
statementposition
is: is set to
statement
00 (and
(and performs
aa possible
possible mark
marka flip(),
to
to which
undefined).
undefined).means
The
The that limit
result
result of
of is
the
theset to
third
thirdposition,
print
print while
statement
statementposition
is:
is: is set to
0 (and a possible mark to undefined). The result of the third print statement is:
0 (and a possible mark to undefined). The result of the third print statement is:
Capacitet: 10
Capacitet: 10
Capacitet:
Limit: 10
3
Capacitet:
Limit: 10
3
Limit:
Position: 03
Limit:
Position: 03
Position:
Remaining: 0
3
Position: 0
Remaining: 3
Remaining: 3
java.nio.HeapByteBuffer[pos=0 lim=3 cap=10]
Remaining: 3
java.nio.HeapByteBuffer[pos=0 lim=3 cap=10]
java.nio.HeapByteBuffer[pos=0 lim=3 cap=10]
java.nio.HeapByteBuffer[pos=0 lim=3 cap=10]
The
The buffer
buffer has
has then
then free
free space
space for
for 3
3 elements.
elements. The
The next
next statement
statement performs
performs aa mark(),
mark(), which
which
The
The
meansbuffer
buffer
thathas
hasthen
thethen free
valuefreeofspace
space
the for
for
index33elements.
elements.
mark is setThe
The
to next
next
the statement
statement
value of performs
performs
position. a
Next amark(),
mark(),which
positionwhich
is set
The
means buffer
that has
thethen
valuefreeof space
the for
index 3 elements.
mark is set The
to next
the statement
value of performs
position. Next a mark(),
positionwhich
is set
means
means
to 2 that
that
and the
thethe value
value
buffer of
is of the
the index
index
reprinted: mark
mark is
is set
set to
to the
the value
value of
of position.
position. Next
Next position
position is
is set
set
means
to 2 that
and thethe value
buffer is of the index
reprinted: mark is set to the value of position. Next position is set
to
to 22 and
and the
the buffer
buffer isis reprinted:
reprinted:
to 2 and the buffer is reprinted:
Capacitet: 10
Capacitet: 10
Capacitet:
Limit: 10
3
Capacitet:
Limit: 10
3
Limit:
Position: 23
Limit:
Position: 23
Position:
Remaining: 2
1
Position: 2
Remaining: 1
Remaining: 1
java.nio.HeapByteBuffer[pos=2 lim=3 cap=10]
Remaining: 1
java.nio.HeapByteBuffer[pos=2 lim=3 cap=10]
java.nio.HeapByteBuffer[pos=2 lim=3 cap=10]
java.nio.HeapByteBuffer[pos=2 lim=3 cap=10]
where
where there
there is
is nothing
nothing to
to explain,
explain, but
but mark
mark has
has the
the value
value 3.
3. The
The next
next statement
statement is
is aa reset():
reset():
where there is nothing to explain, but mark has the value 3. The next statement
statementisisaaareset():
where is reset():
wherethere
thereisisnothing
nothingto
toexplain,
explain,but
butmark
markhas
hasthe
thevalue
value3.3.The
Thenext
nextstatement reset():
Capacitet: 10
Capacitet: 10
Capacitet:
Limit: 10
3
Capacitet:
Limit: 10
3
Limit:
Position: 03
Limit:
Position: 03
Position:
Remaining: 0
3
Position: 0
Remaining: 3
Remaining: 3
java.nio.HeapByteBuffer[pos=0 lim=3 cap=10]
Remaining: 3
java.nio.HeapByteBuffer[pos=0 lim=3 cap=10]
java.nio.HeapByteBuffer[pos=0 lim=3 cap=10]
java.nio.HeapByteBuffer[pos=0 lim=3 cap=10]

82
82
82
82
JAVA
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIOIO java.nIo
java.nio
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nIo
java.nIo

Themethod
The method reset()sets
sets limittotomark
mark whenposition
position is settoto0,0,and
and thenmark
mark is undefined.
The methodreset()
reset() setslimit
limit to markwhen
when positionisisset
set to 0, andthenthen markisisundefined.
undefined.
After
Afterthat
thatlimit
limitand
and position
positionare
areagain
againassigned
assignedthe
thevalues
values 88
After that limit and position are again assigned the values 8 and 3:and
and 3:
3:

Capacitet:
Capacitet: 10
10
Capacitet: 10
Limit:
Limit: 8
Limit: 8
Position:
Position: 3
3
Position: 3
Remaining:
Remaining: 5
Remaining: 5
java.nio.HeapByteBuffer[pos=3
java.nio.HeapByteBuffer[pos=3 lim=8 cap=10]
java.nio.HeapByteBuffer[pos=3 lim=8
lim=8 cap=10]

after
aftera aarewind()
after rewind()
rewind()isis performing.
performing.ItIt
isperforming. Itisis
isa aamethod
method that
methodthat set
thatset position
positiontoto
setposition to0,0, and
0,and any
andany mark
markisis
anymark then
isthen
then
undefined:
undefined:
undefined:

Capacitet: 10
Capacitet: 10
Limit:
Limit: 8
8
Limit: 8
Position:
Position: 0
Position: 0
Remaining:
Remaining: 8
8
Remaining: 8
java.nio.HeapByteBuffer[pos=0
java.nio.HeapByteBuffer[pos=0 lim=8 cap=10]
java.nio.HeapByteBuffer[pos=0 lim=8 cap=10]

Thenext
The next statementperforms
performs a clear(),which
which brieflymeans
means thatallallpointers
pointers areset
set backtoto
The nextstatement
statement performsa aclear(),
clear(), whichbriefly
briefly meansthat
that all pointersare
are setback
back to
start,and
start, andthus
thusasasthey
theywere
wereimmediately
immediatelyafter
afterthe
thebuffer
bufferwas
wascreated:
created:
start, and thus as they were immediately after the buffer was created:

Capacitet:
Capacitet: 10
10
Capacitet: 10
Limit:
Limit: 10
Limit: 10
Position:
Position: 0
0
Position: 0
Remaining:
Remaining: 10
Remaining: 10
java.nio.HeapByteBuffer[pos=0
java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]
java.nio.HeapByteBuffer[pos=0 lim=10
lim=10 cap=10]

The
Thelast two statements creates a new buffer, but this time a abuffer to values of the type long:
The last
last two
two statements
statements creates
creates aa new
new buffer,
buffer, but
but this
this time
time a buffer
buffer to
to values
values of
of the
the type
type long:
long:

Capacitet:
Capacitet: 10
10
Capacitet: 10
Limit:
Limit: 10
10
Limit: 10
Position:
Position: 0
0
Position: 0
Remaining:
Remaining: 10
Remaining: 10
10
java.nio.HeapLongBuffer[pos=0
java.nio.HeapLongBuffer[pos=0 lim=10 cap=10]
java.nio.HeapLongBuffer[pos=0 lim=10
lim=10 cap=10]

As can
canbebe
Ascan
As seen
beseen from
seenfrom the
fromthe example,
theexample, the
example,the type
thetype Buffer
typeBuffer has
hasa aanumber
Bufferhas number
numberofof methods,
ofmethods, which
methods,which among
whichamong
among
otherthings
other things canbebeused
used to manipulatethe the Bufferspointers.
pointers. Thesemethods
methods all returna a
other thingscancan be usedtotomanipulate
manipulate theBuffers
Buffers pointers.These
These methodsallallreturn
return a
Buffer
Buffer object (a reference to the Buffer after the operation is performed), and this means
Bufferobject
object(a(areference
referencetotothe
theBuffer
Bufferafter
afterthe
theoperation
operationisisperformed),
performed),and
andthis
thismeans
means
that, instead
that,instead
that, of writing
insteadofofwriting
writing

buffer.mark();
buffer.mark();
buffer.mark();
buffer.position(2);
buffer.position(2);
buffer.position(2);
buffer.reset();
buffer.reset();
buffer.reset();

8383
83
83
83
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo

you
you can
can write
write

buffer.mark().position(2).reset();

The example
The example shown
shown has
has two
two types
types of
of buffers
buffers

--- ByteBuffer
ByteBuffer
--- LongBuffer
LongBuffer

Both are
Both are examples
examples of of abstract
abstract classes
classes and
and concrete
concrete buffers
buffers are
are created
created using
using static
static methods.
methods.
There are
There are also
also the
the following
following buffer
buffer classes:
classes:

--- CharBuffer
CharBuffer
--- ShortBuffer
ShortBuffer
--- IntBuffer
IntBuffer
--- FloatBuffer
FloatBuffer
--- DoubleBuffer
DoubleBuffer

Excellent Economics and Business programmes at:

The perfect start


of a successful,
international career.

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

84
84
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo

CREATE
CREATE BUFFERS
BUFFERS
There
There are
are several
several ways
ways to
to create
create aa buffer,
buffer, and
and the
the following
following method
method presents
presents four
four options:
options:

private static void test02()


{
byte[] bytes = new byte[500];
print(ByteBuffer.allocate(100));
print(ByteBuffer.allocateDirect(100));
print(ByteBuffer.wrap(bytes));
print(ByteBuffer.wrap(bytes, 10, 300));
}

Generally, aa buffer
Generally, buffer isis an
an encapsulation
encapsulation ofof an
an array,
array, and
and wee
wee talk,
talk, where
where appropriate,
appropriate, ofof aa
backing
backing array,
array, but
but itit need
need not
not be
be the
the case.
case. The
The above
above method
method defines
defines an
an array
array to
to be
be used
used
as
as backing
backing array
array to
to aa buffer.
buffer. The
The most
most common
common way way to
to create
create aa buffer,
buffer, however,
however, isis directly
directly
to apply
to apply the
the method
method allocate()
allocate() as
as in
in the
the first
first example
example above:
above:

Capacitet: 100
Limit: 100
Position: 0
Remaining: 100
java.nio.HeapByteBuffer[pos=0 lim=100 cap=100]

There
There isis not
not much
much to to add
add in
in relation
relation to
to the
the first
first example
example and
and the
the result
result isis aa buffer
buffer having
having
aa capacity
capacity of 100 bytes, and wherein the limit is equal to the capacity and the position isis
of 100 bytes, and wherein the limit is equal to the capacity and the position
0.
0. The
The next
next buffer
buffer isis almost
almost identical:
identical:

Capacitet: 100
Limit: 100
Position: 0
Remaining: 100
java.nio.DirectByteBuffer[pos=0 lim=100 cap=100]

but you
but you should
should note
note that
that the
the types
types are
are different,
different, where
where the
the type
type of
of the
the first
first isis HeapByteBuffer,
HeapByteBuffer,
while the
while the type
type of
of the
the last
last isis DirectByteBuffer.
DirectByteBuffer. The
The difference
difference isis explained
explained later.
later. That
That II am
am
talking about
talking about buffers
buffers to
to bytes,
bytes, isis not
not so
so important,
important, and
and the
the syntax
syntax would
would be be the
the same
same ifif
there instead
there instead were
were talking
talking about
about buffers
buffers toto elements
elements of
of the
the other
other primitive
primitive types.
types.

The third
The third buffer
buffer encapsulates
encapsulates the
the array
array of
of bytes:
bytes:

Capacitet: 500
Limit: 500
Position: 0
Remaining: 500
java.nio.HeapByteBuffer[pos=0 lim=500 cap=500]

85
85
JAVA
JAVA5:5:
JAVA FILES
5:FILES AND
FILESAND JAVA
ANDJAVA IO
JAVAIO
IO java.nIo
java.nio
java.nIo

and
and
andthethe result
resultisis
theresult isaaabuffer
buffer with
withaaacapacity
bufferwith capacity
capacityofof 500
of500 elements,
elements,aaalimit
500elements, limit
limitofof 500
of500
500andand
andaaaposition
position
position
ofof
of0.0.
0.YouYou should
Youshould
shouldnotenote that
notethat
thatthethe capacity
capacityisis
thecapacity determined
isdetermined
determinedby by the
bythe length
lengthofof
thelength the
ofthe array,
thearray, and
array,and the
andthe
the
type
type isis the
the same
same as
as in
in the
the first
first example.
example. The
The last
last buffer
buffer is
is also
also created
created as
as an
an
type is the same as in the first example. The last buffer is also created as an encapsulation encapsulation
encapsulation
ofof the
ofthe array
arrayofof
thearray bytes,
ofbytes, but
bytes,but here
buthere
hereyouyou can
youcan set
setaaaposition
canset position and
andaaalength
positionand length which
lengthwhich means
whichmeans
meansthatthat the
thatthe
the
limit
limit will
limitwill
willbebe position
beposition + length:
position++length:
length:

Capacitet:
Capacitet: 500
500
Limit:
Limit: 310
310
Position: 10
Position: 10
Remaining:
Remaining: 300
300
java.nio.HeapByteBuffer[pos=10 lim=310 cap=500]
java.nio.HeapByteBuffer[pos=10 lim=310 cap=500]

Buffers
Bufferscreated
Buffers createdwith
created withallocate()
with allocate()and
allocate() andwrap()
and wrap()has
wrap() hasaaabacking
has backingarray,
backing array,and
array, andyou
and youcan
you canaccess
can accessthis
access thisarray
this array
array
with
withthe
the method
method array().
array().
with the method array().

You
Youcan
You canalso
can alsocreate
also createaaaso-called
create so-calledview
so-called viewbuffer
view bufferthat
buffer thatisis
that isaaabuffer
bufferthat
buffer thatencapsulates
that encapsulatesaaasecond
encapsulates secondbuffer.
second buffer.
buffer.
The
Thetwo
The twobuffers
two buffershave
buffers havethe
have thesame
the samedata
same dataand
data andhave
and havethe
have thesame
the samecapacity,
same capacity,but
capacity, butthey
but theyeach
they eachhave
each havetheir
have their
their
limit,
limit,position
position and
and mark,
mark, and
and a aview
view buffer
bufferis
issimply
simply a amatter
matter of
ofbeing
being able
able
limit, position and mark, and a view buffer is simply a matter of being able to manipulateto
tomanipulate
manipulate
the
thesame
the samedata
same data(the
data (thesame
(the samebuffer)
same buffer)inin
buffer) inseveral
severalways.
several ways.Consider
ways. Considerthe
Consider thefollowing
the followingmethod:
following method:
method:

private
private static
static void
void test03()
test03()
{
{
byte[] bytes
byte[] bytes == {
{ 0x02,
0x02, 0x03,
0x03, 0x05,
0x05, 0x07,
0x07, 0x0b, 0x0d, 0x11,
0x0b, 0x0d, 0x13 };
0x11, 0x13 };
ByteBuffer buffer1 = ByteBuffer.wrap(bytes);
ByteBuffer buffer1 = ByteBuffer.wrap(bytes);
ByteBuffer
ByteBuffer buffer2
buffer2 = = buffer1.duplicate();
buffer1.duplicate();
IntBuffer
IntBuffer buffer3 = buffer1.asIntBuffer();
buffer3 = buffer1.asIntBuffer();
buffer1.position(4);
buffer1.position(4);
buffer1.limit(6);
buffer1.limit(6);
print(buffer1);
print(buffer1);
print(buffer2);
print(buffer2);
print(buffer3);
print(buffer3);
}
}

The
The method defines a byte array with 88elements used totocreate a ByteBuffer named buffer1.
The method
method defines
defines aa byte
byte array
array with
with 8 elements
elements used
used to create
create aa ByteBuffer
ByteBuffer named
named buffer1.
buffer1.
For
For this object isisused the method duplicate() totocreate aaview buffer named buffer2. Next
For this object is used the method duplicate() to create a view buffer named buffer2. Next
this object used the method duplicate() create view buffer named buffer2. Next
isiscreated
created another
another view
view buffer
buffernamed
named buffer3,
buffer3,but
but this
thistime
time with
with the
the method
method asIntBuffer().
asIntBuffer().
is created another view buffer named buffer3, but this time with the method asIntBuffer().
This
This buffer allows to manipulate the original buffer asaswas it an IntBuffer. As a next step
This buffer
buffer allows
allows to to manipulate
manipulate the
the original
original buffer
buffer as was
was it
it an
an IntBuffer.
IntBuffer. As
As aa next
next step
step
the
the position
positionand
and limit
limit for
forbuffer1
buffer1 are
areset,
set,after
after which
which the
the buffer
buffer it
it is
isprinted:
printed:
the position and limit for buffer1 are set, after which the buffer it is printed:

Capacitet:
Capacitet: 8
8
Limit:
Limit: 6
6
Position:
Position: 44
Remaining:
Remaining: 2
2
java.nio.HeapByteBuffer[pos=4 lim=6 cap=8]
java.nio.HeapByteBuffer[pos=4 lim=6 cap=8]

8686
86
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.nio
java.nIo

There
There isis not
not much
much mystery
mystery inin the
the result,
result, but
but ifif you
you subsequently
subsequently prints
prints buffer2,
buffer2, you
you will
will
see
seethat
thatitithas
hasaadifferent
differentposition
positionandandanother
anotherlimit,
limit,and
andare
arenot
notchanged
changedwhenwhenthe
thebuffer1
buffer1
changes its values:
changes its values:

Capacitet: 8
Limit: 8
Position: 0
Remaining: 8
java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]

sinceaaview
since viewbuffer
bufferhas
hasits
itsown
ownindexes.
indexes.IfIfyou
youprints
printsthe
thelast
lastbuffer,
buffer,you
youget
getthe
theresult:
result:

Capacitet: 2
Limit: 2
Position: 0
Remaining: 2
java.nio.ByteBufferAsIntBufferB[pos=0 lim=2 cap=2]

Its
Its capacity
capacity isis 2.2. The
The array
array has
has elements
elements for
for 88 bytes,
bytes, which
which corresponds
corresponds toto 22 ints,
ints, and
and itit
corresponds
correspondsprecisely
preciselytotothatthatthis
thisview
viewinterprets
interpretsthe
theunderlying
underlyingarray
arrayasasan
anint
intarray.
array.

87
87
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.nio
java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

READ
READAND
ANDWRITE
WRITE
READ AND WRITE
Buffers
Buffersare
areofofcourse
courseonly
onlyinteresting
interestingififyou
youcan
canmodify
modifythe
thecontent,
content,and
andititmeans
meansthat
thatyou
you
Buffers
can are of course only interesting if you can modify the content, and it means that you
canread
readthe
theindividual
individualelements
elementsand
andchange
changethem.
them.This
Thisisisdone
donewith
withput()
put()and
andget(),
get(),and
and
can read
both the individual elementsand
and change them. This is done the
with put() andmethod:
get(), and
bothmethods
methodsare areininan
anabsolute
absolute andaarelative
relativeversion.
version.Consider
Consider thefollowing
following method:
both methods are in an absolute and a relative version. Consider the following method:
private static void test04()
private static void test04()
{
{
byte[] bytes = { 0x02, 0x03, 0x05, 0x07, 0x0b, 0x0d, 0x11, 0x13 };
byte[] bytes = { 0x02, 0x03, 0x05, 0x07, 0x0b, 0x0d, 0x11, 0x13 };
ByteBuffer buffer = ByteBuffer.wrap(bytes);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
printElements(buffer);
printElements(buffer);
buffer.put(3, (byte)23);
buffer.put(3, (byte)23);
buffer.position(6);
buffer.position(6);
buffer.put((byte)29);
buffer.put((byte)29);
bytes[7] = 0x1f;
bytes[7] = 0x1f;
printElements(buffer);
printElements(buffer);
}
}

private static void printElements(ByteBuffer buffer)


private static void printElements(ByteBuffer buffer)
{
{
for (int i = 0; i < buffer.limit(); ++i) System.out.print(buffer.get(i) + " ");
for (int i = 0; i < buffer.limit(); ++i) System.out.print(buffer.get(i) + " ");
System.out.println();
System.out.println();
for (buffer.position(0); buffer.position() < buffer.limit(); )
for (buffer.position(0); buffer.position() < buffer.limit(); )
System.out.print(buffer.get() + " ");
System.out.print(buffer.get() + " ");
System.out.println();
System.out.println();
}
}

Themethod
The method test04()creates
creates a bufferwhichwhich encapsulatesan an arrayofof88elements.
elements. Nextthe the
The methodtest04()
test04() createsaabuffer
buffer whichencapsulates
encapsulates anarray array of 8 elements.Next Next the
methodprints
method prints thecontent
content of thebuffer
buffer in twoways.ways. Thefirstfirst is a regularfor for loop,wherewhere
method printsthe the contentofofthethe bufferinintwotwo ways.The The firstisisaaregular
regular forloop,
loop, where
theindividual
the individual componentsare are referredtotoby
by themethod
method get()and and anindex.
index. Theindividual
individual
the individualcomponents
components arereferred
referred to bythe the methodget()get() andan an index.The The individual
elementsare
elements are referredthusthus byan an absoluteindex,
index, andthe the indexmust must begreater
greater thanoror
elements arereferred
referred thusby by anabsolute
absolute index,and and theindexindex mustbe be greaterthan than or
equal
equal to 0 and less than the limit. The next loop references the elements relative to there
equaltoto00andandless
lessthan
thanthe
thelimit.
limit.The
Thenext
nextlooploopreferences
referencesthe theelements
elementsrelative
relativetotothere
there
position,
position, and the loop starts with setting the position to 0, and then the loop is iterated as
position,and
andthetheloop
loopstarts
startswith
withsetting
settingthe
theposition
positiontoto0,0,andandthen
thenthetheloop
loopisisiterated
iteratedasas
longasasthe
long the positionisislessless thanthethe limit.The
The elementsare are referedwith with get()without
without an
long as theposition
position is lessthan
than thelimit.
limit. Theelements
elements arerefered
refered withget() get() withoutan an
index
index and the method returns the element to what position is pointing to, and then the
indexand
andthethemethod
methodreturns
returnsthetheelement
elementtotowhatwhatposition
positionisispointing
pointingto, to,and
andthenthenthethe
position
position is counted up by 1. This means that when the loop stops, the position is equal to
positionisiscounted
countedup upby
by1.1.This
Thismeans
meansthat
thatwhenwhenthe
theloop
loopstops,
stops,thetheposition
positionisisequal
equaltoto
limit.The
limit. The resultisis
limit. Theresult
result is
2 3 5 7 11 13 17 19
2 3 5 7 11 13 17 19
2 3 5 7 11 13 17 19
2 3 5 7 11 13 17 19

88
88
88
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo
JAVA 5:
JAVA 5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nIo
java.nIo

After
After thethe content
content of of the
the buffer
buffer areare printed
printed thethe elements
elements withwith index
index 33 isis changed
changed to to 23.
23. ItIt isis
After
After the
the content
content of
of the
the buffer
buffer are
are printed
printed the
the elements
elements with
with index
index 3
3 is
is changed
changed to
to 23.
23. It
It isis
by
by the the method
method put()
put() butbut with
with an an absolute
absolute index.
index. You
You should
should notenote that
that this
this operation
operation does
does
by
by the the method put()
method value but with
put() butposition. an absolute
with an absolute index. You should
index. You should note that
note that this operation
this operation does
does
not
not change
change the
the value of of position. NextNext thethe position
position isis set
set toto 66 and
and the
the value
value atat position
position 66 isis
not change
not change the
the value
value of of position.
position. Next
Next thethe position
position is
is set
set toto 66 and
and the
the value
value atat position
position 6 6 isis
changed
changed to to 29.
29. ItIt also
also happens
happens with with put(),
put(), but
but without
without specifying
specifying an an index
index and
and thus
thus relative
relative
changed
changed to
to 29.
29. It
It also
also happens
happens with
with put(),
put(), but
but without
without specifying
specifying an an index
index and
and thus
thus relative
relative
to
to thethe position,
position, and
and after
after the
the operation
operation isis performed,
performed, the the position
position isis counted
counted forward
forward with
with
to the
to Finally position,
the position, and after
andofafter the
the operation
operation is performed,
is performed, the
the position
position is counted
is counted forward
forward with
with
1.
1. Finally the value of the last place in the backing the array is directly changed to 31, and
the value the last place in the backing the array is directly changed to 31, and
1. Finally the value of the last place in
in the backing the array is directly changed to 31, and
the backing the array is directly changed to 31,
is1. Finally
the theprinted
buffer value ofthetheresult
is the buffer printed the result is:
last place
is: and
is the
is the buffer
buffer printed
printed the the result
result is:is:

2 3 5 23 11 13 29 31
2
2 3
3 5
5 23
23 11
11 13
13 29
29 31
31
2 3 5 23 11 13 29 31
2
2 3
3 5
5 23
23 11
11 13
13 29
29 31
31

get() and
get() and put()
put() may
may also
also have
have an
an array
array as
as aa parameter,
parameter, and
and itit can
can be
be used
used to,
to, respectively,
respectively,
get()
get() and
and put()
put() may
may also
also have
have an
an array
array as
as aa parameter,
parameter, and
and it
it can
can be
be used
used to,
to, respectively,
respectively,
get more
get more elements
elements out
out of
of aa buffer
buffer and
and modifying
modifying the
the multiple
multiple elements
elements in
in aa buffer
buffer more
more
get more
get more elements
elements out
out of
of aa buffer
buffer and
and modifying
modifying the
the multiple
multiple elements
elements in
in aa buffer
buffer more
more
efficiently. Consider
efficiently. Consider the
the following
following method:
method:
efficiently.
efficiently. Consider
Consider the
the following
following method:
method:
private static void test05()
private static
private static void
void test05()
test05()
{
{
{ byte[] bytes1 = { 0x02, 0x03, 0x05, 0x07, 0x0b, 0x0d, 0x11, 0x13 };
byte[] bytes1
byte[] bytes1 = {
{ 0x02, 0x03,
0x03, 0x05, 0x07,
0x07, 0x0b, 0x0d,
0x0d, 0x11,
0x11, 0x13 };
byte[] bytes2 =
= { 0x02,
0x17, 0x1d, 0x05,
0x1f, 0x25, 0x0b,
0x2b }; 0x13 };
byte[]
byte[] bytes2
bytes2 = { 0x17,
= { =0x17, 0x1d, 0x1f, 0x25, 0x2b };
0x1d, 0x1f, 0x25, 0x2b };
ByteBuffer buffer ByteBuffer.allocate(8);
ByteBuffer buffer
ByteBuffer buffer == ByteBuffer.allocate(8);
ByteBuffer.allocate(8);
printElements(buffer);
printElements(buffer);
printElements(buffer);
buffer.position(0);
buffer.position(0);
buffer.position(0);
buffer.put(bytes1);
buffer.put(bytes1);
buffer.put(bytes1);
printElements(buffer);
printElements(buffer);
printElements(buffer);
buffer.position(2);
buffer.position(2);
buffer.position(2);
buffer.put(bytes2, 1, 3);
buffer.put(bytes2, 1,
buffer.put(bytes2, 1, 3);
printElements(buffer); 3);
printElements(buffer);
printElements(buffer);
byte[] bytes3 = new byte[4];
byte[] bytes3
byte[] bytes3 = new
new byte[4];
byte[] bytes4 =
= new byte[4];
byte[8];
byte[]
byte[] bytes4
bytes4 = new
= new byte[8];
byte[8];
buffer.position(2);
buffer.position(2);
buffer.position(2);
buffer.get(bytes3);
buffer.get(bytes3);
buffer.get(bytes3);
buffer.position(2);
buffer.position(2);
buffer.position(2);
buffer.get(bytes4, 3, 3);
buffer.get(bytes4,
buffer.get(bytes4, 3,
3, 3);
3);
printElements(ByteBuffer.wrap(bytes3));
printElements(ByteBuffer.wrap(bytes3));
printElements(ByteBuffer.wrap(bytes3));
printElements(ByteBuffer.wrap(bytes4));
printElements(ByteBuffer.wrap(bytes4));
} printElements(ByteBuffer.wrap(bytes4));
}
}

This method creates a buffer with room for 8 elements and prints the contents:
This
This method
This method creates
creates aaa buffer
method creates buffer with
buffer with room
with room for
for 88
room for elements
8 elements and
elements and prints
and prints the
prints the contents:
the contents:
contents:
0 0 0 0 0 0 0 0
0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0
0 0 0 0 0 0 0 0
0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0

89
89
89
89
JAVA
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nIo
java.nIo

That is,
That is, in aa buffer
in buffer created with
with allocate() elements
elements are all
all 0. Next
Next the position
position is set
set to 0
0
That is, in a buffer created
created with allocate()
allocate() elements are
are all 0.
0. Next the
the position is
is set to
to 0
and
and the
the buffer
buffer is
is changed
changed by
by means
means of
of the
the array
array bytes1:
bytes1:
and the buffer is changed by means of the array bytes1:

buffer.put(bytes1);
buffer.put(bytes1);

This
This means
means that
that the
the contents
contents ofof the
the array
array are
are copied
copied toto the
the buffer
buffer and
and from
from the
the starting
starting
position onwards. Therefore, it is necessary to first set position to 0, and after the statement
position onwards. Therefore, it is necessary to first set position to 0, and after the statement
is
is completed,
completed, the
the position
position has
has shifted
shifted eight
eight places
places forward
forward and
and thus
thus to
to the
the end
end of
of the
the buffer.
buffer.
When you then prints the buffer, you
When you then prints the buffer, you get get

2
2 3
3 5
5 7
7 11
11 13
13 17
17 19
19
2
2 3
3 5
5 7
7 11
11 13
13 17
17 19
19

There
There is
is another
another version
version of
of the
the put(),
put(), which
which in
in addition
addition to
to the
the array
array indicates
indicates an
an offset
offset into
into
the array
the array and
and the
the number
number of of elements
elements to
to be
be copied:
copied:

buffer.put(bytes2,
buffer.put(bytes2, 1,
1, 3);
3);

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

enroll by September 30th, 2014 and


save up to 16% on the tuition!
pay in 10 installments / 2 years
Interactive Online education
visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

90
90
90
JAVA
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIOIO java.nio
java.nIo
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nIo
java.nIo

The
Theposition
The positionwas
position waspreviously
was previouslyset
previously settoto
set to2,2,
2,and
andthe
and theresult
the resultisis
result is

2
2
2 3
3
3 29
29
29 31
31
31 37
37
37 13
13
13 17
17
17 19
19
19
2
2
2 3
3
3 29
29
29 31
31
31 37
37
37 13
13
13 17
17
17 19
19
19

where
wherethe
where theplaces
the placeswith
places withindex
with index2,2,
index 2,33
3and
and44
and 4are
areupdated.
are updated.There
updated. Thereare
There aresimilar
are similaroverloadings
similar overloadingsofof
overloadings ofget(),
get(),
get(),
where
where the
where the elements
the elements in
elements inthe
in the buffer
the buffer is
buffer is copied
is copied to
copied to an
to an array.
an array. bytes3
array. bytes3 is
bytes3 is an
is anarray
an arraywith
array withroom
with room for
for44
room for 4
elements,
elements, and the position isisset 2, and the following statement copies the 44elements to
elements, and
and the
the position
position is set
set 2,
2, and
and the
the following
following statement
statement copies
copies the
the 4 elements
elements toto
the
thearray
arraybytes3:
bytes3:
the array bytes3:

buffer.get(bytes3);
buffer.get(bytes3);
buffer.get(bytes3);

Thus,
Thus,
Thus,thethe array
thearray length
arraylength determines
lengthdetermines how
determineshow many
howmany elements
manyelements are
elementsare copied.
copied.IfIf
arecopied. bytes3
bytes3isis
Ifbytes3 encapsulated
isencapsulated
encapsulated
inin
ina aabuffer
buffer and
bufferand printed
andprinted you
printedyou gets
yougets
gets

29
29
29 31
31
31 37
37
37 13
13
13
29
29
29 31
31
31 37
37
37 13
13
13

As
As the
Asthe last
thelast example
exampleisis
lastexample bytes4
bytes4anan
isbytes4 array
anarray with
arraywith room
withroom for
for88
roomfor elements.
8elements. Position
Positionisis
elements.Position again
isagain set
settoto
againset to22
2
and
and are
andare the
arethe follwing
thefollwing statement
follwingstatement performed
statementperformed
performed

buffer.get(bytes4,
buffer.get(bytes4, 3,
buffer.get(bytes4, 3, 3);
3, 3);
3);

the
the elements
elementsatat
theelements positions
positions3,3,
atpositions 3,44 and
and55
4and are
5are copied:
arecopied:
copied:

0
0 0
0 0
0 29
29 31
31 37
37 0
0 0
0
0 0 0 29 31 37 0 0
0
0 0
0 0
0 29
29 31
31 37
37 0
0 0
0
0 0 0 29 31 37 0 0

AA typical
Atypical use
useofof
typicaluse ofa aabuffer
buffer
bufferisis
isa aaprocess
process
process(a(a program)
(aprogram)
program)which which takes
whichtakes
takesupup elements
elementsofof
upelements ofa aabuffer,
buffer, and
buffer,and
and
wherein
wherein
whereinthe the buffer
bufferisis
thebuffer then
isthen connected
connectedtoto
thenconnected toa aachanel,
chanel, which
chanel,which drain
whichdrain (taking
drain(taking elements
(takingelements
elementsfrom)from)
from)the the
the
buffer.
buffer. The
buffer.The following
Thefollowing example
followingexample
exampledefinesdefines an array
definesananarray with
arraywith four
withfour strings
fourstrings
stringsandand a CharBuffer.
anda aCharBuffer.
CharBuffer.Then Then
Then
the method
themethod
the iterates
methoditerates over
iteratesover the
overthe strings
thestrings
stringsandand for
andfor each
foreach string
eachstring the
stringthe buffer
thebuffer is emptied
bufferisisemptied
emptiedthe the method
themethod
method
clear() that
clear()that
clear() sets
thatsets the
setsthe limit
limittoto
thelimit tothe the buffers
thebuffers capacity,
bufferscapacity,
capacity,and and position
positiontoto
andposition to0.0. Next,
Next,anan
0.Next, inner
aninner loop
innerloop
loop
iterates
iterates over
iteratesover each
overeach character
characterinin
eachcharacter the
inthe string
thestring
stringandand fills
andfills the
fillsthe characters
thecharacters
charactersintointo
intothethe buffer.
thebuffer.
buffer.WhenWhen
Whenthe the
the
characters
characters
charactersareare loaded
areloaded
loadedinto into the
intothe buffer,
thebuffer, the
buffer,the buffer
thebuffer is drained
bufferisisdrained
drainedby by the
bythe method
themethod printLine(),
methodprintLine(),
printLine(),whichwhich
which
means
meansthat
means that the
thatthe content
thecontent
contentmust must be printed
mustbebeprinted from
printedfrom
fromthe the position
theposition 0 to
position00totothethe limit.
thelimit. That
limit.That is, the
Thatis,is,the limit
thelimit
limit
should
shouldbebe
should set
settoto
beset tothethe position,
theposition,
position,after after which
afterwhich
whichthe the position
positionisis
theposition istoto
tobebe set
settoto
beset to00 and
0and
andthisthis can
canbebe
thiscan be
done
done with
donewith
withthethe method
methodofof
themethod flip():
offlip():
flip():

9191
91
91
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

private static void test06()


private static void test06()
{
{
String[] names = { "Erik Ejegod", "Erik Emune",
String[] names = { "Erik Ejegod", "Erik Emune",
"Erik Lam", "Erik Plovpenning" };
"Erik Lam", "Erik Plovpenning" };
CharBuffer buffer = CharBuffer.allocate(100);
CharBuffer buffer = CharBuffer.allocate(100);
for (int i = 0; i < names.length; ++i)
for (int i = 0; i < names.length; ++i)
{
{
buffer.clear();
buffer.clear();
for (int j = 0; j < names[i].length(); j++) buffer.put(names[i].charAt(j));
for (int j = 0; j < names[i].length(); j++) buffer.put(names[i].charAt(j));
buffer.flip();
buffer.flip();
printLine(buffer);
printLine(buffer);
}
}
}
}

private static void printLine(CharBuffer buffer)


private static void printLine(CharBuffer buffer)
{
{
while (buffer.hasRemaining()) System.out.print(buffer.get());
while (buffer.hasRemaining()) System.out.print(buffer.get());
System.out.println();
System.out.println();
}
}

Note especially how the method printLine() drains the buffer and how to use hasRemaining()
Note
Noteespecially
especiallyhow
howthethemethod
methodprintLine()
printLine()drains
drainsthe
thebuffer
bufferand
andhow
howto touse
usehasRemaining()
hasRemaining()
to test whether the position is reached to limit. The method test06() is a kind of prototype
to
to test
test whether
whether the
the position
position isis reached
reached to
to limit.
limit. The
The method
method test06()
test06() isis aa kind
kind of
of prototype
prototype
of using a buffer.
of using a buffer.
of using a buffer.

Sometimes you is interested to drain a buffer and then subsequently put the indices back as
Sometimes
Sometimes you
you isis interested
interested to to drain
drain aa buffer
buffer and
and then
then subsequently
subsequently put
put the
the indices
indices back
back as
as
they were before. It is here that the index mark can help. Consider the following method:
they
they were
were before.
before. ItIt isis here
here that
that the
the index
index mark
mark can
can help.
help. Consider
Consider the
the following
following method:
method:
private static void test07()
private static void test07()
{
{
IntBuffer buffer = IntBuffer.allocate(10);
IntBuffer buffer = IntBuffer.allocate(10);
buffer.put(2).put(3).put(5).put(7).put(11).put(13).put(17).put(19);
buffer.put(2).put(3).put(5).put(7).put(11).put(13).put(17).put(19);
buffer.limit(8).position(2).mark().position(6);
buffer.limit(8).position(2).mark().position(6);
print(buffer);
print(buffer);
buffer.reset();
buffer.reset();
print(buffer);
print(buffer);
}
}

private static void print(IntBuffer buffer)


private static void print(IntBuffer buffer)
{
{
while (buffer.hasRemaining()) System.out.print(buffer.get() + " ");
while (buffer.hasRemaining()) System.out.print(buffer.get() + " ");
System.out.println();
System.out.println();
}
}

92
92
92
JAVA 5:
JAVA 5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nIo
java.nIo

This
This method
method creates
creates an
an int
int buffer
buffer with
with room
room for
for 10
10 numbers.
numbers. Next,
Next, 8 8 numbers
numbers are
are added
added
to
to the buffer. Note the syntax, where the use of the method put() returns a reference to
the buffer. Note the syntax, where the use of the method put() returns a reference to the
the
buffer after the element has been added. After the 8 numbers are added the limit
buffer after the element has been added. After the 8 numbers are added the limit is set to is set to
8, position 2, and then set a mark in order to finally set position to 6. Then the following
8, position 2, and then set a mark in order to finally set position to 6. Then the following
show
show the
the indexes:
indexes:

-- limit
limit =
limit =
= 8
8
8
-- position
position
position =
= 6
= 6
6
-- mark
mark =
mark = 2
= 2
2

Then drain
Then the buffer
drain the with the
buffer with method print(),
the method and the
print(), and result is:
the result is:

17
17 19
17 19
19

After
After the
the method
method print()
print() is
is executed,
executed, the
the following
following applies
applies regarding
regarding the
the indices:
indices:

-- limit
limit =
limit =
= 8
8
8
-- position
position
position =
= 8
= 8
8
-- mark
mark =
mark = 2
= 2
2

93
93
93
93
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

The
The method test07() now performs aa reset() and the result of the indexes are
The method
method test07()
test07() now
now performs
performs a reset()
reset() and
and the
the result
result of
of the
the indexes
indexes are
are

-- limit = 8
limit = 8
- position = 2
- position = 2
-- mark = undefined
mark = undefined

and
and the method print() will finally result in
and the
the method
method print()
print() will
will finally
finally result
result in
in

5 7 11 13 17 19
5 7 11 13 17 19

As the
As the last for
for read and
and write II will
will mention the the method compact(),
compact(), which copies
copies all elements
elements
As the last
last for read
read and write
write I will mention
mention the method
method compact(), which
which copies allall elements
between
between the
between the position
the position and
position and limit
and limit to
limit to start
to start of
start of the
of the buffer.
the buffer. After
buffer. After that,
After that, the
that, the position
the position isis
position is equal
equal to
equal to
to
the
the limit
limit
position,
position, while
while the
the limit
limit is
is equal
equal to
to capacity.
capacity. Consider
Consider the
the following
following
the limit position, while the limit is equal to capacity. Consider the following method: method:
method:

private static void test08()


private static void test08()
{
{
IntBuffer in = IntBuffer.allocate(10);
IntBuffer in = IntBuffer.allocate(10);
in.put(2).put(3).put(5).put(7).put(11).put(13).put(17).put(19).put(23).
in.put(2).put(3).put(5).put(7).put(11).put(13).put(17).put(19).put(23).
put(29).rewind();
put(29).rewind();
IntBuffer out = IntBuffer.allocate(10);
IntBuffer out = IntBuffer.allocate(10);
while (in.hasRemaining())
while (in.hasRemaining())
{
{
out.put(in.get());
out.put(in.get());
if (out.position() == 8 && out.get(0) == 2)
if (out.position() == 8 && out.get(0) == 2)
{
{
out.flip().position(2);
out.flip().position(2);
out.compact();
out.compact();
}
}
}
}
print(out);
print(out);
out.clear();
out.clear();
print(out);
print(out);
}
}

IfIf you
If you performs
you performs the
performs the method,
the method, you
method, you get
you get the
get the result
the result
result

0 0
0 0
5 7 11 13 17 19 23 29 0 0
5 7 11 13 17 19 23 29 0 0

94
94
94
JAVA
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.nIo
java.nio
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nIo
java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

which
whichisis not clear. The method starts by creating an IntBuffer
IntBufferinin
which with room for 10 elements,
which isnot
is notclear.
not clear.The
clear. Themethod
The methodstarts
method startsby
starts bycreating
by creatingan
creating anIntBuffer
an IntBuffer inwith
in withroom
with roomfor
room for10
for 10elements,
10 elements,
elements,
which
after
after is
which not
which theclear.
the The
buffer
buffer method
is
is filled
filled starts
with
with 10by
10 creating
numbers.
numbers. an IntBuffer
After
After the
the in with
buffer
buffer isisroom
filled
filled for
isis 10
the
the elements,
position
after which
after which thethe buffer
buffer isis filled
filled with
with 10 10 numbers.
numbers. AfterAfter thethe buffer
buffer is is filled
filled is theposition
is the position
position
after
isis which
equal to the
10, buffer
and is filled
therefore with
the 10 numbers.
initialization is After
finishes the buffer
with a is filled
rewind(), is the
which position
which sets
equal to 10, and therefore the initialization is finishes with a rewind(), which sets the
is
is equal
equal toto 10,
10, andand therefore
therefore the the initialization
initialization isis finishes
finishes withwith aa rewind(),
rewind(), which setsthe
sets the
the
is equal
position
position to
to
to 10,
0.
0. The
The and
nexttherefore
next step
step is
is the
to
to initialization
create
create another
another is finishes
IntBuffer
IntBuffer with
out
out a
with
with rewind(),
room
room for
for which
1010 sets
numbers.
numbers. the
position to 0. The next step is to create another IntBuffer out with
position to 0. The next step is to create another IntBuffer out with room for 10 numbers. room for 10 numbers.
position
The
The to 0. while
following The nextloop step is tothecreate
drains another
buffer in and IntBuffer
fill the out withofroom
elements the for 10out.
buffer numbers.
When
Thefollowing
The followingwhile
following whileloop
while loopdrains
loop drainsthe
drains thebuffer
the bufferinin
buffer inand
andfill
and fillthe
fill theelements
the elementsofof
elements ofthethebuffer
the bufferout.
buffer out.When
out. When
When
The
positionfollowing
position in
in out
out while
isis88 loop
(and
(and drains
the
the first the
first buffer
element
element ofin
of and
the
the fill
buffer
buffer the
isiselements
not
not 2),
2), of
the
the the buffer
following
following out.
is
is When
the
the case
position in
position in out
out isis 8
8 (and
(and the
the first
first element
element ofof the
the buffer
buffer is is not
not 2),
2), the
the following
following is thecase
is the case
case
position
concerning
concerning in out
the
the is 8 (and
indices:
indices: the first element of the buffer is not 2), the following is the case
concerning
concerning the the indices:
indices:
concerning the indices:
--- limit
limit =
limit =
=
10
10
10
-- limit =
position 10
= 8
-- position
position =
= 8
8
- position = 8

Once
Once the
Oncethe position
theposition has
positionhas been
hasbeen reached
reached88
beenreached the
8the method
themethod performs
performsaaaaflip(),
methodperforms flip(), followed
flip(),followed by
byaaaaposition(2),
followedby position(2),
position(2),
Once the position has been reached 8 the method performs flip(), followed by position(2),
Once
and the
the position
indices arehas been reached 8 the method performs a flip(), followed by a position(2),
and
andthe
and theindices
the indicesare
indices are
are
and the indices are
--- limit
limit =
limit =
=
8
8
8
-- limit =
position 8= 2
-- position
position =
= 2
2
- position = 2

At that
Atthat
At time,
thattime, the
time,the content
contentofof
thecontent the
ofthe buffer
bufferisis
thebuffer is
At that time, the content of the buffer is
At that time, the content of the buffer is
2
2 3
3 5
5 7
7 11
11 13
13 17
17 19
19
2 3 5 7 11 13 17 19
2 3 5 7 11 13 17 19

and then there


thereisis performed
performedaaaacompact()
and then there is performed compact()
compact() to copy the elements from the index 2 through 7
and
andthen
thenthere isperformed compact()toto copy
tocopy the
copythe elements
theelements from
elementsfrom the
fromthe index
index22
theindex through
through77
2through 7
and
to then
the there
start of is
the performed
buffer: a compact() to copy the elements from the index 2 through 7
tothe
toto thestart
the startofof
start ofthe
thebuffer:
the buffer:
buffer:
to the start of the buffer:
5
5 7
7 11
11 13
13 17
17 19
19 17
17 19
19
5 7 11 13 17 19 17 19
5 7 11 13 17 19 17 19

and
and
and the
the indices
indices which
which now
now applies
applies
andthe
theindices
indiceswhich
whichnow
nowapplies
applies
and the indices which now applies
--- limit
limit =
= 10
10
limit = 10
-- limit =
position 10
= 8 2 = 6
-- position
position =
= 8
8
2
2 =
= 6
6
- position = 8 2 = 6

The while loop adds two more elmenter


elmentertoto out (the numbers 23 and 29), which
whichisis
The on the
Thewhile
The whileloop
while loopadds
loop addstwo
adds twomore
two moreelmenter
more elmenter toout
to out(the
out (thenumbers
(the numbers23
numbers 23and
23 and29),
and 29),which
29), which ison
is onthe
on the
the
The while
places withloop adds
index 6 two
and 7more
and elmenter
for the to out
indices (the
apply numbers 23 and 29), which is on the
places
placeswith
with index
index66and
and7 7and
andfor
forthe
theindices
indicesapply
apply
places with index 6 and 7 and for the indices apply
places with index 6 and 7 and for the indices apply
--- limit
limit =
limit = 10
= 10
10
-- limit
position = 10= 8
-- position
position = = 88
- position = 8
The
Thefirst print() outside the loop therefore prints:
The first
The first print()
first print() outside
print() outside the
outside the loop
the loop therefore
loop therefore prints:
therefore prints:
prints:
The first print() outside the loop therefore prints:
0
0 0
0
0 0
0 0

9595
95
95
95
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

Before
Before the
the last
last print()
print() is
is performed,
performed, aa clear()
clear() is
is executed
executed that
that sets
sets the
the position
position to
to 00 and
and the
the
Before
limit the last print() is performed, a clear() is executed that sets the position to 0 and the
limit to
to capacity,
capacity, and
and the
the result
result is
is therefore
therefore
limit to capacity, and the result is therefore
5 7 11 13 17 19 23 29 0 0
5 7 11 13 17 19 23 29 0 0

LAST REMARKS ABOUT BUFFERS


LAST REMARKS ABOUT BUFFERS
It is possible to compare two buffers with equals(), and the protocol is as follows:
It is possible to compare two buffers with equals(), and the protocol is as follows:

Two buffers are equals() if and only if they have the same element type, they have the same
Two buffers are equals() if and only if they have the same element type, they have the same
number of remaining elements, and the two sequences of remaining elements, considered
number of remaining elements, and the two sequences of remaining elements, considered
independently of their starting positions, are individually equal.
independently of their starting positions, are individually equal.

As an example, the following method prints true:


As an example, the following method prints true:
private static void test09()
private static void test09()
{
{
IntBuffer buff1 = IntBuffer.allocate(10);
IntBuffer buff1 = IntBuffer.allocate(10);
buff1.put(0). put(1).put(2).put(3).put(5).put(7).put(11).put(13).put(17).put(19);
buff1.put(0). put(1).put(2).put(3).put(5).put(7).put(11).put(13).put(17).put(19);
buff1.position(2);
buff1.position(2);
buff1.limit(6);
buff1.limit(6);

96
96
96
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

IntBuffer buff2 = IntBuffer.allocate(8);


IntBuffer buff2 = IntBuffer.allocate(8);
buff2.put(2).put(3).put(5).put(7);
buff2.put(2).put(3).put(5).put(7);
buff2.flip();
buff2.flip();
System.out.println(buff1.equals(buff2));
} System.out.println(buff1.equals(buff2));
}
First
First notice
notice that
that the
the two
two buffers
buffers are
are of
of different
different lengths.
lengths. buff1
buff1 has
has position
position 22 and
and limit
limit 66
First
while notice that the two buffers are of different lengths. buff1 has position 2 and limit 6
while buff2
buff2 have
have position
position 00 and
and limit
limit 4,
4, but
but itit means
means that
that both
both buffers
buffers have
have four
four remaining
remaining
while buff2 have
elements position 0 and limit 4,inbut it means that both buffers have four remaining
elements and
and these
these elements
elements are
are equal
equal in pairs.
pairs.
elements and these elements are equal in pairs.
The
The last
last observation
observation relates
relates to
to performance.
performance. Currently,
Currently, aa buffer
buffer isis nothing
nothing but but aa memory
memory
The last
structure observation relates to performance. Currently, a buffer is nothing but a memory
structure that encapsulates an array, and in relation to files is the meaning of course that
that encapsulates an array, and in relation to files is the meaning of course that
structure
the IO that encapsulates
system must copy an array,
data to and and
fromin the
relation to Somewhere
buffers. files is the meaning
it is not of coursesince
optimal, that
the IO system must copy data to and from the buffers. Somewhere it is not optimal, since
the IO system must copy data to andare from thetheir
buffers. Somewhere it is not optimal, since
the operating
operating systems
systems IO
IO operations
operations are using
using their ownown buffers
buffers that
that do do not have
have anything
anything
the
with operating systemsbuffers
IO operations are usingthis
their own buffers that do not have anything
with Java
Java toto do,
do, but
but buffers as as described
described in in this section
section are
are data
data structures
structures forfor JVM,
JVM, and and
with Java ittowill
therefore do,bebutadvantageous
buffers as described
that they inwere
thisthe
section
same are data structures
buffers. It is, for JVM,
however, not and
quite
therefore it will be advantageous that they were the same buffers. It is, however, not quite
therefore
simple, it will be advantageous that they were the same buffers. It is, however, not quite
simple, in in particular
particular due
due toto the
the Javas
Javas buffers
buffers are
are not
not necessarily
necessarily contiguous
contiguous allocated,
allocated, but
but
simple,
also in particular due to the Javas buffers are not necessarily contiguous allocated, but
also because
because the the garbage
garbage collector
collector ifif necessary
necessary areare moving
moving them.
them. In In an an attempt
attempt to to solve
solve
also
these because
problems,the garbage
one can collector
create a if
byte necessary
buffer as are moving them. In an attempt to solve
these problems, one can create a byte buffer as
these problems, one can create a byte buffer as
ByteBuffer buffer = ByteBuffer.allocateDiect(99);
ByteBuffer buffer = ByteBuffer.allocateDiect(99);

It is a buffer that is associated with the IO and files, and in some cases, results in an
It is a buffer that is associated with the IO and files, and in some cases, results in an
improved in performance and defines a buffer without a backing array, but there must be
improved in performance and defines a buffer without a backing array, but there must be
special reasons for using that kind of buffers, since the gain is typically small.
special reasons for using that kind of buffers, since the gain is typically small.

3.2 CHANNELS
3.2 CHANNELS
3.2 CHANNELS
Channels belongs to buffers to achieve high-performance I/O. A channel is an object that
Channels belongs to buffers to achieve high-performance I/O. A channel is an object that
represents an open connection to a hardware device as a file. Channels efficiently transfer
represents an open connection to a hardware device as a file. Channels efficiently transfer
data between byte buffers and operating system-based I/O services, and often there exists a
data between byte buffers and operating system-based I/O services, and often there exists a
one-to-one correspondence between a file descriptor and a channel. When you work with
one-to-one correspondence between a file descriptor and a channel. When you work with
channels in a file context, the channel will often be connected to an open file.
channels in a file context, the channel will often be connected to an open file.

A channel is defined by an interface


A channel is defined by an interface
java.nio.channels.Channel
java.nio.channels.Channel

97
97
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIOIO java.nio
java.nIo
JAVA 5: FILES AND JAVA IO java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

The
Theinterface
interfaceonly
onlydefines
definestwo
twomethods
methodsclose()
close()and
andisOpen(),
isOpen(),and
andthe
themethods
methodsfor
forIO
IOare
are
The
The interface
defined in two
interface only defines
subinterfaces
only defines two
two methods
methods close()
close() and
and isOpen(),
isOpen(), and
and the
the methods
methods for
for IOare
IO are
defined in two subinterfaces
definedinintwo
defined twosubinterfaces
subinterfaces
java.nio.channels.WritableByteChannel
java.nio.channels.WritableByteChannel
java.nio.channels.WritableByteChannel
java.nio.channels.ReadableByteChannel
java.nio.channels.ReadableByteChannel
java.nio.channels.ReadableByteChannel

thereasasthe
there thenames
namessays
saysdefines
defineschannels
channelsfor
forwriting
writingororreading.
reading.AAclass
classthat
thatonly
onlyimplements
implements
thereasasthe
there thenames
namessays
saysdefines
defineschannels
channelsfor
forwriting
writingororreading.
reading.AAclass
classthat
thatonly
onlyimplements
implements
oneofofthis
one thisinterfaces
interfacesisiscalled
calledunidirectional,
unidirectional,and
anda aclass
classthe
theimplements
implementsboth
bothinterfaces
interfacesisis
oneofofthis
one thisinterfaces
interfacesisiscalled
calledunidirectional,
unidirectional,and
andaaclass
classthe
theimplements
implementsboth
bothinterfaces
interfacesisis
calledbidirectional.
called bidirectional.
calledbidirectional.
called bidirectional.

Thereare
There areseveral
severalways
waystotocreate
createa achannel
channeltotoa afile
fileand
andthus
thusa aChannel
Channelobject.
object.The
Theclass
class
Thereare
There areseveral
severalways
waystotocreate
createaachannel
channeltotoaafile
fileand
andthus
thusaaChannel
Channelobject.
object.The
Theclass
class
Channelshas
Channels hastwo
twostatic
staticmethods:
methods:
Channelshas
Channels hastwo
twostatic
staticmethods:
methods:
WritableByteChannel writer = Channels.newChannel(OutputStream stream)
WritableByteChannel writer
WritableByteChannel writer = Channels.newChannel(OutputStream stream)
stream)
ReadableByteChannel reader == Channels.newChannel(OutputStream
Channels.newChannel(InputStream stream)
ReadableByteChannel reader = Channels.newChannel(InputStream stream)
ReadableByteChannel reader = Channels.newChannel(InputStream stream)

Finally, several of the classes in the java.io are extended with a method getChannel(), which
Finally,several
Finally,
Finally, severalof
ofofthe
theclasses
classesin
ininthe
thejava.io
java.ioare
areextended
extendedwith
withaaamethod
methodgetChannel(),
getChannel(),which
which
returnsseveral
a Channel. the classes the java.io are extended with method getChannel(), which
returnsaaaChannel.
returns
returns Channel.
Channel.
I will now show an example that uses two Channel objects to copy a file. The example
II Iwill
willnow
will nowshow
now showan
show anexample
examplethat thatuses
usestwo twoChannel
Channelobjectsobjectsto tocopy
copyaaafile.
file.The
Theexample
example
assumes that my an example
home that
directory uses
has a two Channel
subdirectory objects
data withto acopy file.
file named The example
municipalities,
assumesthat
assumes
assumes thatmy
that myhome
homedirectory
directoryhas hasaaasubdirectory
subdirectorydata datawith
withaaafilefilenamed
namedmunicipalities,
municipalities,
which has a my
size home
of 2863 directory has
bytes (the textsubdirectory
file with the data with
names file
of Danish named municipalities,
municipalities, but
whichhas
which
which hasaaasize
has sizeof
size of2863
of 2863bytes
2863 bytes(the
bytes (thetext
(the textfile
text filewith
file withthe
with thenames
the namesof
names ofofDanish
Danishmunicipalities,
Danish municipalities,but
municipalities, but
but
is not important what the file contains, as long as it is found in the right directory and has
isis
is notimportant
not
a not
importantwhat
sizeimportant
between 2what
whatthethefile
and the
filecontains,
file
3 KB).
contains,asaslong
contains,
Consider as
longas
long
first
asit
ititis
isisfound
theasfollowing
foundin
found ininthe
method:
theright
the rightdirectory
right directoryand
directory andhas
and has
has
aaasize
sizebetween
size between222and
between and333KB).
and KB).Consider
KB). Considerfirst
Consider firstthe
first thefollowing
the followingmethod:
following method:
method:
private static void copy1(ReadableByteChannel src, WritableByteChannel dst)
private static
private static void
void copy1(ReadableByteChannel
copy1(ReadableByteChannel src,
src, WritableByteChannel
WritableByteChannel dst)
dst)
throws IOException
throws IOException
{ throws IOException
{
{ ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteBuffer buffer
ByteBuffer buffer == ByteBuffer.allocate(1024);
ByteBuffer.allocate(1024);
while (src.read(buffer) != -1)
while
while (src.read(buffer)
(src.read(buffer) != != -1)
-1)
{
{{ buffer.flip();
buffer.flip();
buffer.flip();
dst.write(buffer);
dst.write(buffer);
dst.write(buffer);
buffer.compact();
buffer.compact();
} buffer.compact();
}}
buffer.flip();
buffer.flip();
buffer.flip();
dst.write(buffer);
dst.write(buffer);
} dst.write(buffer);
}}

98
98
98
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.nio
java.nIo

The
Themethod
methodhas hastwo
twoparameters
parametersthatthatareareboth
bothunidirectional
unidirectionalChannelChannelobjects,
objects,wherein
whereinthe the
first
firstone
oneisisfor
forreading
readingand andthe
thesecond
secondone oneisisfor
forwriting.
writing.The Themethod
methodcreates
createsaabuffer,
buffer,and
and
the
theonly
onlything
thingyouyoushould
shouldnotice
noticeis,is,that
thatthe
thesize
sizeisissmaller
smallerthanthanthethefile.
file.Next,
Next,the
themethod
method
performs
performsaaloop loopthat
thatiterates
iteratesso
solong
longasasthere
thereisisdata
dataon onthe theinput
inputchannel.
channel.Each
Eachiteration
iteration
performs
performs aa flip()
flip() ofof the
the buffer
buffer and
and then
then writing
writing thethe buffer
buffer toto the
the output
output channel
channel asas the
the
method
methodwrite()
write()drains
drainsthe thebuffer.
buffer.You
Youmust
mustnote
notethat
thatititisisall
allbytes
bytesfrom
fromthetheposition
position00totothe
the
limit
limitandandafter
afterthe
theoperation
operationthe theposition
positionisisequal
equaltotolimit.
limit.Next,
Next,isisperformed
performedaacompact()
compact()
statement,
statement,whichwhichcopies
copiesdepending
dependingbytesbytesafter
afterthe
thelimit
limittotothethestart
startofofthe
thebuffer.
buffer.This
Thisisistoto
ensure
ensurethatthatthethebuffer
bufferdoesdoesnot
notcontain
containdata,
data,which
whichisisnot notdrained
drainedtotothe theoutput
outputchannel.
channel.
After
Afterthetheloop
loopstops
stopsall alldata
dataononthetheinput
inputchannel
channelisisread readthe themethod
methodperforms
performsagain
again
aaflip()
flip()and
andthe thebuffer
bufferisisdrained
drainedtotothe theoutput
outputchannel.
channel.

The
Thefollowing
followingmethod
methodcreates
createsananinput
inputchannel
channeltotoan
anInputStream
InputStreamand
andan
anoutput
outputchannel
channel
totoan
anOutputStream
OutputStreamand
anduse
usethe
theabove
abovemethod
methodtotocopy
copyaafile:
file:

private static void test10()


{
ReadableByteChannel src = null;
WritableByteChannel dst = null;
try
{

Join the best at Top masters programmes


3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
1st place: MSc International Business
School of Business and 1st place: MSc Financial Economics
2nd place: MSc Management of Learning

Economics! 2nd place: MSc Economics


2nd place: MSc Econometrics and Operations Research
2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier Beste Studies ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Masters Open Day: 22 February 2014

www.mastersopenday.nl

99
99
JAVA 5: FILES AND JAVA IO java.nio
JAVA5:
JAVA
JAVA 5:FILES
5: FILESAND
FILES ANDJAVA
AND JAVAIO
JAVA IO
IO java.nIo
java.nIo
java.nIo

src === Channels.newChannel(new


src
src Channels.newChannel(new FileInputStream(
Channels.newChannel(new FileInputStream(
FileInputStream(
System.getProperty("user.home") +++ "/data/municipalities"));
System.getProperty("user.home")
System.getProperty("user.home") "/data/municipalities"));
"/data/municipalities"));
dst === Channels.newChannel(new
dst
dst Channels.newChannel(new FileOutputStream("municipalities1"));
Channels.newChannel(new FileOutputStream("municipalities1"));
FileOutputStream("municipalities1"));
copy1(src,
copy1(src, dst);
dst);
copy1(src, dst);
}}}
catch (IOException
catch
catch (IOException ex)
(IOException ex)
ex)
{{{
System.out.println("I/O error:
System.out.println("I/O
System.out.println("I/O error: """ +++ ex.getMessage());
error: ex.getMessage());
ex.getMessage());
}}}
finally
finally
finally
{{{
try
try
try
{{{
if (src
if
if (src !=
(src != null)
!= null) src.close();
null) src.close();
src.close();
if (dst
if
if (dst !=
(dst != null)
!= null) dst.close();
null) dst.close();
dst.close();
}}}
catch (IOException
catch
catch (IOException ex)
(IOException ex)
ex)
{{{
System.out.println("I/O error:
System.out.println("I/O
System.out.println("I/O error: """ +++ ex.getMessage());
error: ex.getMessage());
ex.getMessage());
}}}
}}}
}}}

There isis not


There is
There not much
not much to
much to explain,
to explain, but
explain, but you
but you must
you must note
must note how
note how to
how to create
to create the
create the two
the two Channel
two Channel objects.
Channel objects.
objects.

Below isis another


Below is
Below another example
another example on
on aaa method
example on method that
method that copies
copies aaa file
that copies file by
file by means
by means of
means of two
of two Channel
two Channel objects:
Channel objects:
objects:

private static
private
private static void
static void copy2(ReadableByteChannel
void copy2(ReadableByteChannel src,
copy2(ReadableByteChannel src, WritableByteChannel
src, WritableByteChannel dst)
WritableByteChannel dst)
dst)
throws IOException
throws IOException
throws IOException
{{
{
ByteBuffer buffer
ByteBuffer
ByteBuffer buffer === ByteBuffer.allocate(4096);
buffer ByteBuffer.allocate(4096);
ByteBuffer.allocate(4096);
while (src.read(buffer)
while
while (src.read(buffer) !=
(src.read(buffer) != -1);
!= -1);
-1);
buffer.flip();
buffer.flip();
buffer.flip();
dst.write(buffer);
dst.write(buffer);
dst.write(buffer);
}
}}

The difference
The difference
The difference is isis that
that this
that this time
this time the
time the entire
the entire input
entire input file
input file isis copied
file is copied
copied toto the
to the buffer
the buffer before
buffer before
before ititit is
isis
drained to
drained to
drained the
to the output
the output channel.
output channel. This
channel. This method
This method
method is isis simpler
simpler than
simpler than the
than the previous
the previous one,
previous one, but
one, but there
but there
there is isis
an important
an
an important condition,
important condition, that
condition, that the
that the buffer
the buffer has
buffer has enough
has enough space
enough space to
space to contain
to contain all
contain all the
all the input
the input file.
input file. The
file. The
The
test method
test method
test method isisis as
as follows
as follows
follows

private static
private
private static void
static void test11()
void test11()
test11()
{{{
try (ReadableByteChannel
try
try (ReadableByteChannel src
(ReadableByteChannel src ===
src
Channels.newChannel(new FileInputStream(
Channels.newChannel(new
Channels.newChannel(new FileInputStream(
FileInputStream(
System.getProperty("user.home") +++ "/data/municipalities"));
System.getProperty("user.home")
System.getProperty("user.home") "/data/municipalities"));
"/data/municipalities"));

100
100
100
100
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

WritableByteChannel
WritableByteChannel dst
dst =
=
Channels.newChannel(new
Channels.newChannel(new FileOutputStream("municipalities2")))
FileOutputStream("municipalities2")))
{
{
copy2(src,
copy2(src, dst);
dst);
}
}
catch
catch (IOException
(IOException ex)
ex)
{
{
System.out.println("I/O
System.out.println("I/O error:
error: "
" +
+ ex.getMessage());
ex.getMessage());
}
}
}
}

and
and here isisthe main difference, that the two Channel objects are created asaspart of the try
and here
here is the
the main
main difference,
difference, that
that the
the two
two Channel
Channel objects
objects are
are created
created as part
part of
of the
the try
try
statement.
statement.
statement.

MULTIPLE
MULTIPLE BUFFERS
MULTIPLE BUFFERS
BUFFERS
AsAs shown inin the above examples is aa Channel a fundamental technique to stream data
As shown
shown in the the above
above examples
examples is is a Channel
Channel aa fundamental
fundamental technique
technique to to stream
stream data
data
between
between two end points, that for example can be files, and asas an adapter between the
between two end points, that for example can be files, and as an adapter between the
two end points, that for example can be files, and an adapter between the
channel
channel and
and the
the program
program there
there isisaabuffer.
buffer.For
For many
many years
years one
oneofofthe
themost
mostimportant
important ways
ways
channel and the program there is a buffer. For many years one of the most important ways
totoincrease your computers performence has been parallelism, a technique that particular
to increase
increase your
your computers
computers performence
performence has has been
been parallelism,
parallelism, aa technique
technique that
that particular
particular
operating
operating system exploits and ititalso applies ininconnection with IO. Among other things
operating system exploits and it also applies in connection with IO. Among other things
system exploits and also applies connection with IO. Among other things
for
forthis
this reason
reason Channel
Channel objects
objects supports
supports the
theuse
use ofofmultiple
multiple buffers
buffers where
where an
an input
input channel
channel
for this reason Channel objects supports the use of multiple buffers where an input channel
can
can fill several buffers, while an output channel can drain multiple buffers. The following
can fill
fill several
several buffers,
buffers, while
while an an output
output channel
channel can can drain
drain multiple
multiple buffers.
buffers. The
The following
following
example
example will show the syntax:
example will will show
show the
the syntax:
syntax:

public
public static
static void
void test12()
test12()
{
{
try
try ((
ScatteringByteChannel
ScatteringByteChannel src src == (ScatteringByteChannel)
(ScatteringByteChannel) Channels.newChannel(
Channels.newChannel(
new
new FileInputStream(System.getProperty("user.home") +
FileInputStream(System.getProperty("user.home") + "/data/regions"));
"/data/regions"));
WritableByteChannel out = Channels.newChannel(System.out);
WritableByteChannel out = Channels.newChannel(System.out);
GatheringByteChannel
GatheringByteChannel dst dst = =
(GatheringByteChannel)
(GatheringByteChannel) Channels.newChannel(new FileOutputStream("regions1")))
Channels.newChannel(new FileOutputStream("regions1")))
{
{
ByteBuffer[]
ByteBuffer[] buffers
buffers ==
{
{ ByteBuffer.allocateDirect(100), ByteBuffer.allocateDirect(50)
ByteBuffer.allocateDirect(100), ByteBuffer.allocateDirect(50) }; };
src.read(buffers);
src.read(buffers);
for
for (int
(int ii == 0;
0; ii <
< buffers.length;
buffers.length; ++i)
++i)
{
{
buffers[i].flip();
buffers[i].flip();
out.write(buffers[i]);
out.write(buffers[i]);
System.out.println("\n");
System.out.println("\n");
buffers[i].rewind();
buffers[i].rewind();
}
}

101
101
101
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo

dst.write(buffers);
}
catch (IOException ex)
{
System.out.println("I/O error: " + ex.getMessage());
}
}

After try are created three channels. An input channel, that uses multiple buffers, and is
After try are created three channels. An input channel, that uses multiple buffers, and is
called a scattering channel. It is created as other input channels, and therefore it is necessary
called a scattering channel. It is created as other input channels, and therefore it is necessary
with a typecast. This time, the channel is connected to the file regions for the simple
with a typecast. This time, the channel is connected to the file regions for the simple
reason that the file size is small. The second channel is a usual output channel, which is
reason that the file size is small. The second channel is a usual output channel, which is
connected to System.out, while the third is also an output channel connected to a file in
connected to System.out, while the third is also an output channel connected to a file in
the current directory.
the current directory.

The first statement in the try block creates an array with two ByteBuffer objects. This time
The first statement in the try block creates an array with two ByteBuffer objects. This time
I have used allocateDirect(), which is in principle the most effective buffer for files, but the
I have used allocateDirect(), which is in principle the most effective buffer for files, but the
important thing is that neither of the buffers can store the entire file regions. Note that the
important thing is that neither of the buffers can store the entire file regions. Note that the
two buffers are not of the same size, what is not needed. The next statement performs a
two buffers are not of the same size, what is not needed. The next statement performs a
read on the input channel, wherein the array of buffers are a parameter. The read() method
read on the input channel, wherein the array of buffers are a parameter. The read() method
will read the input channel and fill the content into the two buffers.
will read the input channel and fill the content into the two buffers.

> Apply now

redefine your future


AxA globAl grAduAte
progrAm 2015
- Photononstop

axa_ad_grad_prog_170x115.indd 1 19/12/13 16:36

102
102
JAVA
JAVA
JAVA5:
5:
5:FILES
FILES
FILESAND
AND
ANDJAVA
JAVA
JAVAIO
IO
IO java.nio
java.nIo
java.nIo

The
The next
next for
for loop
loop iterates
iterates to
to the
the two
two buffers,
buffers, and
and for
for each
each iteration
iteration the
the buffer
buffer isis fliped
fliped and
and
drained
drained to to standard
standard output,
output, andand finally
finally isis perform
perform aa rewind()
rewind() so so that
that the
the buffer
buffer can can bebe
drained
drained again.
again. After
After the
the loop
loop the
the two
two buffers
buffers are
are drained
drained to to the
the output
output channel
channel with with the
the
method
method write(),
write(), which
which here
here drains
drains both
both buffers.
buffers. That
That aa channel
channel in in this
this way
way drains
drains more
more
buffers
buffers isis called
called gathering.
gathering. The
The output
output channel
channel isis created
created asas another
another output
output channel,
channel, and and itit
isis therefore
therefore necessary
necessary with
with aa typecast
typecast when
when the the channel
channel isis created.
created.

IfIf the
the method
method isis performed,
performed, you
you get
get results:
results:

1081,
1081, Region
Region Nordjylland
Nordjylland
1082,
1082, Region
Region Midtjylland
Midtjylland
1083,
1083, Region
Region Syddanmark
Syddanmark
1084,
1084, Region
Region Hovedstade
Hovedstade
nn
1085,
1085, Region Sj
Region Sj
lland
lland

and you
and you should
should notice
notice how
how thethe first
first buffer
buffer isis filled
filled to
to its
its capacity,
capacity, while
while the the other
other only
only isis
partially
partially filled.
filled. You
You may
may also
also notice
notice that
that there
there isis aa small
small encoding
encoding error
error (System.out),
(System.out), but but ifif you
you
look at
look at the
the file
file regions1
regions1 in
in the
the current
current directory,
directory, you you will
will see
see that
that the
the file
file isis copied
copied correctly.
correctly.

FILE CHANNELS
FILE CHANNELS

FileChannel isis aa class


FileChannel class that
that represents
represents aa channel
channel to
to files.
files. AA FileChannel
FileChannel isis an
an abstract
abstract class,
class,
but you
but you can
can create
create anan object
object by
by using
using the
the method
method getChannel(),
getChannel(), which
which isis supported
supported by by
several
several of
of the
the classes
classes inin java.io.
java.io. As
As an
an example
example isis below
below shown
shown aa method
method that that copies
copies the
the
file municipalities
file municipalities using
using FileChannel
FileChannel objects:
objects:

private
private static
static void
void test13()
test13()
{{
try
try (FileChannel
(FileChannel src
src == (new
(new FileInputStream(
FileInputStream(
System.getProperty("user.home")
System.getProperty("user.home") ++ "/data/municipalities")).getChannel();
"/data/municipalities")).getChannel();
FileChannel
FileChannel dst
dst == (new
(new FileOutputStream("municipalities3")).getChannel())
FileOutputStream("municipalities3")).getChannel())
{{
copy2(src,
copy2(src, dst);
dst);
}}
catch
catch (IOException
(IOException ex)
ex)
{{
System.out.println("I/O
System.out.println("I/O error:
error: "" ++ ex.getMessage());
ex.getMessage());
}}
}}

103
103
103
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo

The
The method
method isis inin principle
principle the
the same
same as
as test11(),
test11(), butbut the
the two
two Channel
Channel objects
objects are
are created
created
in
in aa different
different way.
way. The The class
class FileInputStream
FileInputStream have
have aa method
method getChannel(),
getChannel(), which
which returns
returns aa
FileChannel.
FileChannel. It It isis aa read-only
read-only channel.
channel. Likewise,
Likewise, the the class
class FileOutputStream
FileOutputStream has
has aa method
method
getChannel(),
getChannel(), which
which returns
returns aa file
file channel
channel that
that isis aa writeonly
writeonly channel.
channel.

Similarly,
Similarly, thethe class
class RandomAccessFile
RandomAccessFile has
has aa method
method getChannel(),
getChannel(), which
which returns
returns aa FileChannel,
FileChannel,
that
that isis aa readwrite
readwrite channel.
channel. The
The class
class FileChannel
FileChannel has
has many
many methods,
methods, and
and II will
will mention
mention
the
the most
most important:
important:

--- void
void force(boolean
force(boolean meta)
meta) which
which enforces
enforces that
that allall updates
updates are are written
written physically
physically to to
the
the file.
file. The
The parameter
parameter specifies
specifies where
where thethe files
files metadata
metadata also also should
should bebe written.
written.
--- long
long position()
position() that
that returns
returns thethe position
position of of the
the physical
physical file
file pointer.
pointer.
--- FileChannel
FileChannel position(long
position(long newPosition)
newPosition) that that sets
sets the
the position
position of of the
the physical
physical filefile
pointer.
pointer. With
With that
that method
method you you can
can define
define where
where to to read
read oror write
write in
in the
the file.
file.
--- int
int read(ByteBuffer
read(ByteBuffer buffer)
buffer) that
that reads
reads bytes
bytes inin the
the file
file and
and returns
returns the
the number
number af af bytes
bytes
as
as read.
read. TheThe maximum
maximum number number of of bytes
bytes isis determined
determined by by the
the capacity
capacity of
of the
the buffer.
buffer.
--- int
int read(ByteBuffer
read(ByteBuffer buffer,
buffer, long
long position)
position) which
which also also reads
reads bytes
bytes toto buffer,
buffer, but
but postion
postion
tells
tells where
where in in the
the file
file to
to start
start (the
(the postion
postion of of the
the file
file pointer).
pointer).
--- long
long size()
size() that
that returns
returns the the size
size ofof the
the file.
file.
--- int
int write(ByteBuffer
write(ByteBuffer buffer)
buffer) that
that writes
writes the
the content
content of of the
the buffer
buffer toto the
the file
file starting
starting
from
from the the current
current position
position of of the
the file
file pointer.
pointer. The The method
method returns
returns the
the number
number og og
bytes
bytes written
written toto the
the file.
file.
--- int
int write(ByteBuffer
write(ByteBuffer buffer,
buffer, long
long position)
position) which
which alsoalso writes
writes bytes
bytes to
to the
the file,
file, but
but
postion
postion tells
tells where
where in in the
the file
file to
to start
start (the
(the postion
postion of of the
the file
file pointer).
pointer).

As
As an
an example,
example, isis shown
shown aa method
method that
that writes
writes to
to and
and reads
reads from
from aa RandomAccessFile:
RandomAccessFile:

public static void test14()


{
try (FileChannel fc = (new RandomAccessFile("numbers", "rw")).getChannel())
{
System.out.println("Position = " + fc.position() + ", size = " + fc.size());
ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
buffer.putInt(23);
buffer.putDouble(Math.PI);
buffer.putInt(29);
buffer.putDouble(Math.E);
buffer.flip();
fc.write(buffer);
fc.force(false);
System.out.println("Position = " + fc.position() + ", size = " + fc.size());

104
104
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo

buffer.clear();
fc.position(0);
fc.read(buffer);
buffer.flip();
System.out.println(buffer.getInt());
System.out.println(buffer.getDouble());
System.out.println(buffer.getInt());
System.out.println(buffer.getDouble());
}
catch (Exception ex)
{
System.out.println("I/O error: " + ex.getMessage());
}
}

105
105
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIOIO java.nio
java.nIo

First
Firsta aFileChannel
FileChannelisisopend
opendtotothe thefile,
file,and
andthis
thistime
timeits
itsa areadwrite
readwritechannel,
channel,and andthe
thefirst
first
thing
thingthat
thathappens
happensisisthat thatthe
themethod
methodprintsprintsthe
theposition
positionofofthe thefile
filepointer
pointerand andfile
filesize.
size.
Next,
Next,a aByteBuffer
ByteBufferisiscreated.
created.I Inow nowwant wanttotowrite
writeananint, int,a adouble,
double,ananint intandandanother
another
double
doubletotothis
thisbuffer.
buffer.InInorderordertotoformat
formatthese
thesevalues
valuesforforbytes
bytesI Iexploit
exploitthatthata aByteBuffer
ByteBuffer
has
hasmethods
methodsfor forthis
thispurpose,
purpose,which whichpartly
partlycopies
copiesthethevalues
valuesintointothe
thebuffer
bufferandandmoves
movesthe the
index
indexposition
positioncorrectly.
correctly.After
Afterthe
thefour
fourvalues
valuesare
arewritten
writtentotothe thebuffer
buffera aflip()
flip()isisperformed,
performed,
and
andthethebuffers
bufferscontents
contentsare aresent
senttotothethechannel.
channel.Then
Thenempty
emptythe thebuffer
bufferandandthe thefile
filepointer
pointer
isisset
set0,0,and
andthe
thecontents
contentsofofthe thefile
fileare
areread
readtotothethebuffer.
buffer.Finally,
Finally,the
theresult
resultisisprinted,
printed,
and
andagain
againareareused
usedthe
therightrightget
getmethods
methodsfor forreading
readingfrom fromthe thebuffer.
buffer.IfIfthethemethod
methodisis
performed,
performed,the theresult
resultis:is:

Position = 0, size = 24
Position = 24, size = 24
23
3.141592653589793
29
2.718281828459045

MEMORY
MEMORYMAPPED
MAPPEDFILES
FILES

AAFileChannel
FileChannelhashasa amethod
methodmap()
map()which
whichmakes
makesititpossible
possibletotoembed
embedananopen
openfile
fileorora apart
part
ofofananopen
openfile
fileinina abuffer:
buffer:

MappedByteBuffer
MappedByteBuffermap(FileChannel.MapMode
map(FileChannel.MapModemode,
mode,long
longposition,
position,long
longsize)
size)

The
Thethree
threeparameters
parametersdenotes denotesa amode
modeininaddition
additiontotothethepart
partofofthe
thefile
filetotobebeencapsulated
encapsulated
(start
(startposition
positionand andthe thelength
lengthofofthe
thesegment
segmenttotobebeencapsulated).
encapsulated).Mode Modemay maybebeREAD_ READ_
ONLY
ONLYororREAD_WRITE.
READ_WRITE.The Thetype
typeMappedByteBuffer
MappedByteBufferhas hasthe
thesame
samecharacteristics
characteristicsasasother other
buffers,
buffers,but
butitsitscontent
contentisisstored
storedinina afile.
file.This
Thismeans
meansfor forexample,
example,thatthatififyou
youperforms
performsa a
get()
get()and
andthe
thefilefileisisupdated
updatedby byanother
anotherprogram,
program,sosothe thechanges
changesarearevisible
visibleininthe thecurrent
current
program.
program.The Thesamesameapplies
appliestotoput()
put()that
thatififyouyouupdate
updatethe thebuffer,
buffer,the
thechange
changewill willbebevisible
visible
ininanother
anotherprograms
programsthat thatuses
usesthe
thesame
samefile.file.The
Thegoal
goalofofa amemory
memorymapped
mappedfile fileisisofofcourse
course
performance,
performance,and andespecially
especiallywhen
whenprocessing
processinglargelargefiles
fileslike
likepictures.
pictures.AsAsananexample
exampleisisshownshown
a amethod
methodthatthatcreates
createsa afile
filewith
with1000
1000integers:
integers:

private static void test15()


{
try (FileChannel fc = (new RandomAccessFile("numbers", "rw")).getChannel())
{
MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_WRITE, 0, 4096);
for (int i = 0; i < 1000; ++i) buffer.putInt(i + 1);
}

106
106
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5:
JAVA 5: FILES AND
AND JAVA IO
IO java.nIo
JAVA 5: FILES
FILES AND JAVA
JAVA IO java.nIo
java.nIo

catch
catch (IOException ex)
catch (IOException
(IOException ex)
ex)
{
{
{
System.out.println("I/O
System.out.println("I/O error: " + ex.getMessage());
System.out.println("I/O error:
error: "
" +
+ ex.getMessage());
ex.getMessage());
}
}
}
}
}
}

The
The file
file is
is aa RandomAccessFile
RandomAccessFile and and asas in
in the
the previous
previous example
example is is created
created aa FileChannel
FileChannel to
to
the
the file.
the file. Next
file. Next
Next isis created
is created a MemoryMappedBuffer
created aa MemoryMappedBuffer
MemoryMappedBuffer to to the
to the channel
the channel
channel and and
and thethe buffer
the buffer says
buffer says that
says that
that
the
the file
file will
will be
be mapped
mapped from
from start
start to
to byte
byte 4096.
4096. This
This number
number corresponds
corresponds
the file will be mapped from start to byte 4096. This number corresponds exactly to that exactly
exactly to
to that
that
the
the file
the file must
file must contains
must contains 1000
contains 1000 integers
1000 integers of
integers of type
of type int.
type int. The
int. The next
The next loop
next loop fills
loop fills the
fills the buffer
the buffer with
buffer with 1000
with 1000
1000
integers
integers from 1 to 1000. You should note that the result of the buffer is written to the file
from 1 to 1000. You should note that the result of the buffer is written to the file
that
that will
that will contain
will contain
contain thethe 1000
the 1000 integers.
1000 integers. Note
integers. Note also
Note also that
also that since
that since it
since it is
it is a difference
is aa difference row,
difference row, the
row, the sum
the sum of
sum of
of
the
the numbers
numbers are
are
the numbers are 500500.500500.
500500.

The
The next
next method
method updates
updates the
the file:
file:

private static
private static void test16()
test16()
private static void
void test16()
{
{
{
try (FileChannel
try (FileChannel fc = = (new RandomAccessFile("numbers",
RandomAccessFile("numbers", "rw")).getChannel())
try (FileChannel fcfc = (new
(new RandomAccessFile("numbers", "rw")).getChannel())
"rw")).getChannel())
{
{
{
MappedByteBuffer buffer
MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_WRITE,
fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size());
fc.size());
MappedByteBuffer buffer = = fc.map(FileChannel.MapMode.READ_WRITE, 0,
0, fc.size());
for (int
for (int
(int ii =
i = 0;
= 0;
0; ii
i << 1000;
< 1000; ++i)
1000; ++i) buffer.putInt(2
++i) buffer.putInt(2
buffer.putInt(2 * * buffer.getInt(i
buffer.getInt(i *
* buffer.getInt(i * 4));
4));
for * 4));
}
}
}
catch
catch (IOException
(IOException ex)
ex)
catch (IOException ex)
{
{
{
System.out.println("I/O
System.out.println("I/O error:
error: "" +
+ ex.getMessage());
ex.getMessage());
System.out.println("I/O error: " + ex.getMessage());
}
}
}
}
}

Again
Again is
is created
created aa memory
memory mapped
mapped file
file and
and all
all data
data in
in the
the file
file is
is updated
updated by
by doubling.
doubling. You
You
should notice how the individual numbers are referenced:
should notice how the individual numbers are referenced:

buffer.getInt(i *
buffer.getInt(i 4)
buffer.getInt(i *
* 4)
4)

returns an
returns an int,
int, starting
starting at
at the
the address
address 4*i,
4*i, but
but without
without moving
moving the
the buffers
buffers position.
position.
The statement
The statement

buffer.putInt(2
buffer.putInt(2 *
* buffer.getInt(i
buffer.getInt(i *
* 4));
4));
buffer.putInt(2 * buffer.getInt(i * 4));

then
then updates
updates the
the same
same int,
int, and
and then
then move
move the
the position
position 4
4 bytes
bytes forward.
forward.
then updates the same int, and then move the position 4 bytes forward.

107
107
107
107
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo

Since
Since all
all numbers
numbers are
are doubled,
doubled, the
the sum
sum of
of the
the numbers
numbers in
in the
the file
file then
then is
is 1001000.
1001000. It
It is
is
validated
validated by
by the
the following
following method:
method:

private static void test17()


{
try (FileChannel fc = (new RandomAccessFile("numbers", "r")).getChannel())
{
long sum = 0;
MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
while (buffer.hasRemaining()) sum += buffer.getInt();
System.out.println(sum);
}
catch (IOException ex)
{
System.out.println("I/O error: " + ex.getMessage());
}
}

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

108
108
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.nio
java.nIo

LOCKING
LOCKINGFILES
FILES

AsAsthe
thelast
lastrelated
relatedtotochannels
channelsI Iwillwilllook
lookatatfile
filelocking.
locking.ItItisispossible
possibletotoput putaalock lockon onan an
entire
entirefile
fileororjust
juston onaapart
partofofaafile,
file,where
wherethethelock
lockindicates,
indicates,where
whereininthe thefile
filelocking
lockingbegins
begins
ofofwhat
whatarea areaininthethefile
filetotobebelocked.
locked.Locking
Lockingoccursoccursatatprocess
processlevel level(and
(andnot notthreads),
threads),
and
andI Iwill
willininthis
thiscontext
contextdistinguish
distinguishbetween
betweenaawriterwriterprocess
process(a(aprocess
processthatthatwrites
writestotothe the
file)
file)and
andaareader
readerprocess
process(a(aprocess
processthat
thatsimply
simplyreads
readsfrom
fromthethefile).
file).There
Thereare aretwotwokinds
kindsofof
locks.
locks.AAwriter
writerprocess
processcancansetsetan
anexclusive
exclusivelock
lockon onaapart
partofofaafile,
file,andandititcan
cando dososoififthere
there
are
arenonoother
otherprocesses
processesthat thathave
haveputputaalock
lockthat
thatoverlaps
overlapsthethepart
partofofthe thefile
filetotobe belocked.
locked.
AnAnexclusive
exclusivelock lockgives
givesthe
thewriter
writerprocess
processfull
fullcontrol
controloveroverthe
thelocked
lockedpartpartofofthe thefile
filesuch
such
that
thatititcan
canboth
bothreadreadandandwrite.
write.AAreader
readerprocess
processcan canput
putaashared
sharedlocklockon onaapart
partofofthethefile,
file,
and
andititcancando dososoififnotnotanother
anotherprocess
processhas hasput
putan anexclusive
exclusivelock
lockthat thatoverlaps
overlapsthe thepart
partofof
the
thefile
filetotobebelocked.
locked.ThisThismeans
meansthat thatthe
theseveral
severalprocesses
processescancanset setaashared
sharedlock lockforforthethe
same
samepartpartofofaafile,
file,and
andthus
thusthat
thatmore
moreprocesses
processescan canread
readthe
thefile.
file.

AAlock
lockhas
hasthe
thetype
typeFileLock
FileLockand
andthe
theFileChannel
FileChannelclass
classhas
hasfour
fourmethods
methodstotocreate
createaalock:
lock:

1.
1.lock()
lock()
2.
2.lock(long
lock(longposition,
position,long
longsize,
size,boolean
booleanshared)
shared)
3.
3.tryLock()
tryLock()
4.
4.tryLock(long
tryLock(longposition,
position,long
longsize,
size,boolean
booleanshared)
shared)

The
Thefirst
firstand
andthethethird
thirdcreates
createsan anexclusive
exclusivelock
lockon
onthetheentire
entirefile,
file,while
whilethetheother
othertwotwocan
can
specify
specifythe
thepart
partofofthethefile
filetotobe
belocked
lockedand andwhere
wherethethelock
lockshould
shouldbe beexclusive
exclusiveororshared.
shared.
The
Thedifference
differenceisisfurther
furtherthat
thatthe
thefirst
firsttwo
twoblocks,
blocks,which
whichisistotosay
saythat
thatififthey
theyare
areunable
unabletoto
lock,
lock,they
theyare
areset
setininaaqueue
queueuntiluntilthey
theycancanget
getthe
thelock,
lock,after
afterwhich
whichthetheprocess
processisisrunning
running
automatically
automaticallyagain
againwhenwhenthe thelock
lockisisreleased.
released.The
Thelast
lasttwo
twomethods
methodsare arenot
notblocking,
blocking,butbutifif
they
theycan
cannot
notcreate
createthe thelock,
lock,they
theywill
willreturn
returnnull,
null,and
andthat
thatisisup
uptotothe
theprogram
programtotodecide
decide
what
whatisistotohappen
happennext. next.

The
Theclass
classFileLock
FileLockhas
hasaanumber
numberofofmethods
methodsthat
thatcan
canreturn
returnthe
theinformation
informationon onthe
thelock
lock
and
andits
itsconditions,
conditions,but
butmost
mostimportantly
importantlyisisthe
themethod
methodrelease()
release()which
whichisisused
usedtotorelease
release
the
thelock.
lock.Universally,
Universally,one
oneuses
usesthe
thefollowing
followingpattern
patterntotolock
lockaafile:
file:

FileLock lock = fileChannel.lock();


try
{
// interact with the file channel
}
catch (IOException ex)
{

109
109
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

// handle the exception


// handle the exception
}
}
finally
finally
{
{
lock.release();
lock.release();
}
}

and here
hereitit
andhere
and itisis important
isimportant
importantthatthat the
thatthe method
themethod release()
release()isis
methodrelease() performed
performedinin
isperformed inaaafinally
finally block,
block,soso
finallyblock, that
sothat
that
one is sure
oneisissure
one that
surethat it is executed.
thatititisisexecuted.
executed.

To illustrate
Toillustrate
To file
illustratefile locking
lockinginin
filelocking practice
practiceI IIhave
inpractice have written
havewritten following
writtenfollowing program
followingprogram Locking:
programLocking:
Locking:

package locking;
package locking;

import java.util.*;
import java.util.*;
import java.io.*;
import java.io.*;
import java.nio.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.channels.*;

public class Locking


public class Locking
{
{
private static final Random rand = new Random();
private static final Random rand = new Random();
private static final int N = 1000000;
private static final int N = 1000000;

public static void main(String[] args)


public static void main(String[] args)
{
{
boolean writer = args.length != 0;
boolean writer = args.length != 0;
try (FileChannel fc =
try (FileChannel fc =
(new RandomAccessFile("integers", (writer) ? "rw" : "r").getChannel()))
(new RandomAccessFile("integers", (writer) ? "rw" : "r").getChannel()))
{
{
if (writer) write(fc); else read(fc);
if (writer) write(fc); else read(fc);
}
}
catch (Exception ex)
catch (Exception ex)
{
{
System.out.println("I/O error: " + ex.getMessage());
System.out.println("I/O error: " + ex.getMessage());
}
}
}
}
private static void read(FileChannel fc) throws Exception
private static void read(FileChannel fc) throws Exception
{
{
for (int i = 0; i < N; i++)
for (int i = 0; i < N; i++)
{
{
System.out.println("Want a shared lock");
System.out.println("Want a shared lock");
long t1 = System.nanoTime();
long t1 = System.nanoTime();
FileLock lock = fc.lock(0, 16, true);
FileLock lock = fc.lock(0, 16, true);
long t2 = System.nanoTime();
long t2 = System.nanoTime();

110
110
110
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo

System.out.println("Has a shared lock " + (t2 t1));


try
{
ByteBuffer buffer = ByteBuffer.allocate(16);
fc.read(buffer, 0);
buffer.flip();
System.out.println("Sum = " +
(buffer.getInt() + buffer.getInt() + buffer.getInt() + buffer.getInt()));
}
finally
{
lock.release();
System.out.println("Shared lock released");
}
}
}
private static void write(FileChannel fc) throws Exception
{
for (int i = 0; i < N; i++)
{
System.out.println("Want an exclusive lock");
long t1 = System.nanoTime();
FileLock lock = fc.lock();
long t2 = System.nanoTime();

Brain power By 2020, wind could provide one-tenth of our planets


electricity needs. Already today, SKFs innovative know-
how is crucial to running a large proportion of the
worlds wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

111

111
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo

System.out.println("Has an exclusive lock: " + (t2 t1));


try
{
ByteBuffer buffer = ByteBuffer.allocate(16);
int value = rand.nextInt(89997) + 10000;
System.out.println("Writing: " + value);
buffer.putInt(value).putInt(value + 1).putInt(value + 2).putInt(value + 3);
buffer.flip();
fc.write(buffer, 0);
}
finally
{
lock.release();
System.out.println("Exclusive lock released");
}
}
}
}

The program is implemented as a command that may have an argument on the command
The program is implemented as a command that may have an argument on the command
line. The value does not matter, but in main(), a boolean writer is true or false depending
line. The value does not matter, but in main(), a boolean writer is true or false depending
on whether there is an argument or not. In main() is created a RandomAccessFile that is
on whether there is an argument or not. In main() is created a RandomAccessFile that is
readwrite or readonly depending on the value of the variable writer, and the same variable
readwrite or readonly depending on the value of the variable writer, and the same variable
is used to determine whether to perform a method write() or a method read().
is used to determine whether to perform a method write() or a method read().

The method write() iterates a loop 1000000 times and for each iteration the method acquire
The method write() iterates a loop 1000000 times and for each iteration the method acquire
an exclusive lock for the file. When the file has been locked the method prints, how long it
an exclusive lock for the file. When the file has been locked the method prints, how long it
has been waiting for the lock, and then writes 4 integers to file before releasing the lock again.
has been waiting for the lock, and then writes 4 integers to file before releasing the lock again.

The method read() works in principle in the same way, just trying the method instead to
The method read() works in principle in the same way, just trying the method instead to
get a shared lock, and instead of writing to the file it reads the 4 integers and prints their
get a shared lock, and instead of writing to the file it reads the 4 integers and prints their
sum on the screen.
sum on the screen.

The idea is now to start two versions of the program, such they runs in each their terminal,
The idea is now to start two versions of the program, such they runs in each their terminal,
and where the one writes, while the other reads. You will then be able to observe how the two
and where the one writes, while the other reads. You will then be able to observe how the two
programs alternately get a lock. It is important that the program that writes is started first.
programs alternately get a lock. It is important that the program that writes is started first.

3.3 PATH AND FILES


3.3 PATH AND FILES
Paths represents the file system, and the class Path is playing the same role as the class File
Paths represents the file system, and the class Path is playing the same role as the class File
in java.io, but Path represents a more general concept and provides many more services
in java.io, but Path represents a more general concept and provides many more services
available. In the following, a Path object refer a path to a file or a directory, but it does not
available. In the following, a Path object refer a path to a file or a directory, but it does not
have to be an existing file or directory, and so a Path is just a name.
have to be an existing file or directory, and so a Path is just a name.

112
112
JAVA
JAVA5:
5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.nio
java.nIo

Along
Along with
with the
the class
class Path
Path isis also
also the
the class
class Files,
Files, and
and both
both classes
classes are
are in
in the
the package
package java.
java.
nio.file.
nio.file. The
The class
class Files
Files isis very
very comprehensive,
comprehensive, but but generally
generally itit contains
contains what
what isis needed
needed to to
manipulate
manipulate thethe file
file system.
system. The The following
following areare not
not be be aa complete
complete documentation
documentation of of these
these
classes,
classes, and
and you
you are
are encouraged
encouraged partlypartly to
to examine
examine the the package
package java.nio.file
java.nio.file and
and what
what types
types
exist
exist and
and specific
specific the
the documentation
documentation for for the
the class
class Files,
Files, so
so you
you have
have an an idea
idea of
of what
what this
this
class
class makes
makes available.
available.

In
Inthe
therest
restof
ofthis
thissection
sectionand
andthus
thusthetherest
restof
ofthis
thischapter,
chapter,IIwill
willthrough
throughsomesomesimple
simpletesting
testing
methods
methods show
show aa little
little of
of what
what isis possible
possible and
and how
how to
to apply
apply the
the two
two classes
classes Path
Path and
and Files.
Files.

THE
THE CLASS
CLASS PATH
PATH

AA path
path isis composed
composed of of aa number
number of of elements
elements (file
(file names)
names) separated
separated by by aa separator,
separator, which
which
isis aa character
character that
that in
in Linux
Linux isis /,/, while
while under
under Windows
Windows itit isis \.\. The
The following
following method
method prints
prints
information
information about about aa Path
Path while
while alsoalso providing
providing an
an introduction
introduction to to some
some of
of the
the methods
methods that
that
the
the class
class Path
Path makes
makes available:
available:

private static void print(Path p)


{
System.out.println(p); // the path
System.out.println(p.getFileName()); // the last element in the path
System.out.println(p.getName(0)); // the 0th element in the path
System.out.println(p.getNameCount()); // number of elements in the path
System.out.println(p.subpath(0,2)); // the two first elements in the path
System.out.println(p.getParent()); // the parent directory
System.out.println(p.getRoot()); // the root directory
System.out.println(p.toUri()); // the part converted to an URL
try
{
Path path = p.toRealPath();
System.out.println(path);
}
catch (Exception ex)
{
System.out.println(ex);
}
System.out.println(p.getFileSystem());
System.out.print
ln("-----------------------------------------------------");
}

113
113
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo

Below
Below isis aa test
test method
method using
using the
the above
above method:
method:

public static void test18()


{
Path p1 = Paths.get("/home/pa/data");
Path p2 = Paths.get("/home/pa/data/zipcodes");
Path p3 = Paths.get("home", "pa", "data");
Path p4 = Paths.get(FileSystems.getDefault().getSeparator(), "home", "pa",
"data", "zipcodes");
Path p5 = Paths.get(System.getProperty("user.home"));
Path p6 = Paths.get("abc").toAbsolutePath();
print(p1);
print(p2);
print(p3);
print(p4);
print(p5);
print(p6);
}

114
114
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.nio
java.nIo

The
Theclass
classPaths
Pathsisisaaclass
classthat
thatinclude
includeaastatic
staticmethod
methodget(),
get(),which
whichyouyoucancanuse
usetotocreate
create
aa Path
Path object.
object. The
The first
first two
two statements
statements areare easy
easy enough
enough toto understand
understand and and they
they creates
creates
(on
(onmymymachine)
machine)aapath pathto,to,respectively,
respectively,aadirectory
directoryand andaafile.
file.The
Thenext
nexttwo
twostatements
statements
does
does almost the same, but here you specify multiple arguments where the argumentsare
almost the same, but here you specify multiple arguments where the arguments are
the
theelements
elementsofofthe thepath
pathand andthethemethod
methodthentheninserts
insertsthe
thenecessary
necessaryseparation
separationcharacters.
characters.
Actually
Actuallyititisisrecommend
recommendtotouse usethis
thissyntax,
syntax,asasininthis
thisway
waymakes
makesthethename
nameregardless
regardlessofof
the
thecurrent
currentoperating
operatingsystem.
system.TheThefirst,
first,however,
however,willwillcreate
createaarelative
relativepath,
path,while
whilethe theother
other
creates an absolute path, and the example should among other things
creates an absolute path, and the example should among other things show how to obtain show how to obtain
the
thefile
filesystem
systemseparation
separationcharacter
characterand andthus
thusthethesymbol
symbolforforroot.
root.The
Thelast
lasttwo
twoexamples
examples
should
shouldshowshowhowhowtotoget getaapath
pathtotothethehome
homedirectory,
directory,andandhowhowtotocreate
createananabsolute
absolutepathpath
for
foraaname.
name.IfIfthethefirst
firstpath
pathisisprinted,
printed,thetheresult
resultis:is:

/home/pa/data
data
home
3
home/pa
/home/pa
/
file:///home/pa/data/
/home/pa/data
sun.nio.fs.LinuxFileSystem@4e25154f

IfIfyou
youlook
lookatatthe
theresults,
results,there
thereisisnot
notsosomuch
muchwonder
wonderininthat,
that,but
butyou
youshould
shouldnote
notehow
how
there
thereisiscreated
createdananURLURLfor forthe
thename.
name.TheThemethod
methodperforms
performsthe thestatement
statementtoRealPath(),
toRealPath(),
which
which creates a Path object to an existing directory or file. This statment is placedininaatry
creates a Path object to an existing directory or file. This statment is placed try/ /
catch,
catch,and
andififthe
thefile
filedoes
doesnot
notexist,
exist,you
youget
getan
anexeption.
exeption.InInthis
thiscase,
case,the
thefile
file(the
(thedirectory)
directory)
exists
existsand
andthethepath
pathisisprinted.
printed.Finally,
Finally,the
thelast
lastline
lineisisincluded
includedonlyonlytotoshow
showhow howtotorefer
refer
totothe
thecurrent
currentfile
filesystem.
system.

The
Theresults
resultscorresponding
correspondingtotothethevariables
variablesp2,
p2,p3,
p3,p4
p4and
andp5
p5contains
containsininprinciple
principlenothing
nothing
new,
new,but
butfor
forthe
thevariable
variablep3
p3isisthe
theresult:
result:

home/pa/data
data
home
3
home/pa
home/pa
null
file:///home/pa/doc/java/Java%205/source05/NIOProgram/home/pa/data
java.nio.file.NoSuchFileException: home/pa/data
sun.nio.fs.LinuxFileSystem@4e25154f

115
115
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nio
java.nIo
JAVA 5: FILES AND JAVA IO java.nIo

and
and here
here you
you must
must note
note that
that itit isis aa relative
relative file
file name,
name, and
and that
that names
names URL
URL as as the
the name
name
and here you must note that it is a relative file name, and that names URL as the name
of
of the
the current
current directory
directory followed
followed by by thethe relative
relative file
file name.
name. You
You should
should also
also note
note that
that this
this
of the current directory followed by the relative file name. You should also note that this
time there is an exception when performing toRealPath() when the directory
time there is an exception when performing toRealPath() when the directory does not exist. does not exist.
time there is an exception when performing toRealPath() when the directory does not exist.
Something
Something similar
similar isis happened
happened with with p6: p6:
Something similar is happened with p6:
/home/pa/doc/java/Java 5/source05/NIOProgram/abc
/home/pa/doc/java/Java 5/source05/NIOProgram/abc
abc
abc
home
home
8
8
home/pa
home/pa
/home/pa/doc/java/Java 5/source05/NIOProgram
/home/pa/doc/java/Java 5/source05/NIOProgram
/
/
file:///home/pa/doc/java/Java%205/source05/NIOProgram/abc
file:///home/pa/doc/java/Java%205/source05/NIOProgram/abc
java.nio.file.NoSuchFileException:
java.nio.file.NoSuchFileException:
/home/pa/doc/java/Java 5/source05/NIOProgram/abc
/home/pa/doc/java/Java 5/source05/NIOProgram/abc
sun.nio.fs.LinuxFileSystem@4e25154f
sun.nio.fs.LinuxFileSystem@4e25154f

abc is the name of a nonexistent file, and the method toAbsolutPath() creates a path which
abc is the name of a nonexistent file, and the method toAbsolutPath() creates a path which
references to a file abc under current directory. The file is not existing, so you get back an
references to a file abc under current directory. The file is not existing, so you get back an
exception when performing toRealPath().
exception when performing toRealPath().

As another example the method below creates a Path object to a file named numbers and
As another example the method below creates a Path object to a file named numbers and
under my tmp directory. Next, the method uses the class Files that have a static method
under my tmp directory. Next, the method uses the class Files that have a static method
newOutputStream(), which creates an OutputStream to a file identified by a Path object. If the
newOutputStream(), which creates an OutputStream to a file identified by a Path object. If the
file does not exist, it is created (if possible), and then there is written 100 bytes to the file:
file does not exist, it is created (if possible), and then there is written 100 bytes to the file:

private static void test19()


private static void test19()
{
{
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/numbers");
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/numbers");
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path)))
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path)))
{
{
for (byte b = 0; b < 100; ++b) out.write(b);
for (byte b = 0; b < 100; ++b) out.write(b);
} catch (IOException ex)
} catch (IOException ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

116
116
116
JAVA5:
JAVA 5:FILES
FILESAND
ANDJAVA
JAVAIO
IO java.nIo
java.nio

THECLASS
THE CLASSFILES
FILES

The class
The class Files
Files isis asas mentioned,
mentioned, very
very comprehensive
comprehensive and
and hashas among
among other
other things
things aa number
number
of static
of static methods
methods that that can
can print
print information
information about
about aa files
files attributes:
attributes:

private static void test20()


{
info(Paths.get("/home/pa/tmp"));
info(Paths.get("/home/pa/tmp/numbers"));
}

private static void info(Path path)


{
System.out.println(Files.exists(path));
System.out.println(Files.isDirectory(path));
System.out.println(Files.isRegularFile(path));
System.out.println(Files.isReadable(path));
System.out.println(Files.isWritable(path));
System.out.println(Files.isExecutable(path));
System.out.println(Files.isSymbolicLink(path));
System.out.print
ln("-----------------------------------------------------");
}

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

117
117
JAVA
JAVA5:5:
5: FILES AND
AND JAVA
FILESAND IO
JAVAIO
IO java.nIo
java.nIo
JAVA
JAVA 5:FILES
FILES ANDJAVA
JAVA IO java.nio
java.nIo

where
where numbers
numbers are
are the
the file
file created
created above.
above. The
The meaning
meaning of each method should follow from
where
wherenumbers
numbersare
arethe
thefile
filecreated
createdabove.
above.The meaningofof
Themeaning each
ofeach method
eachmethod should
methodshould follow
shouldfollow from
followfrom
from
the
the name,
name, and
and is
is the
the method
method perform
perform is
is the
the result:
result:
the
thename,
name,and
andisisthe
themethod
methodperform
performisisthe
theresult:
result:
true
true
true
true
true
true
false
false
false
true
true
true
true
true
true
true
true
true
false
false
false
-----------------------------------------------------
-----------------------------------------------------
-----------------------------------------------------
true
true
true
false
false
false
true
true
true
true
true
true
true
true
true
false
false
false
false
false
false
-----------------------------------------------------
-----------------------------------------------------
-----------------------------------------------------

Consider
Consider then the following method:
Considerthen
Consider thenthe
then thefollowing
the followingmethod:
following method:
method:
private
private static void test21()
private static
static void
void test21()
test21()
{
{
{
try
try
try
{
{
{
Path p0
Path = Paths.get(System.getProperty("user.home"));
Path p0
p0 == Paths.get(System.getProperty("user.home"));
Paths.get(System.getProperty("user.home"));
Path
Path p1 = Files.createDirectory(p0.resolve("testdir"));
Path p1
p1 == Files.createDirectory(p0.resolve("testdir"));
Files.createDirectory(p0.resolve("testdir"));
Path p2
Path p2 == Files.createFile(p1.resolve("testfile"));
Path p2 = Files.createFile(p1.resolve("testfile"));
Files.createFile(p1.resolve("testfile"));
System.out.println(p0);
System.out.println(p0);
System.out.println(p0);
System.out.println(p1);
System.out.println(p1);
System.out.println(p1);
System.out.println(p2);
System.out.println(p2);
System.out.println(p2);
Files.copy(p2, p1.resolve("testfile1"));
Files.copy(p2, p1.resolve("testfile1"));
Files.copy(p2, p1.resolve("testfile1"));
System.out.println(Files.deleteIfExists(p1.resolve("testfile1")));
System.out.println(Files.deleteIfExists(p1.resolve("testfile1")));
System.out.println(Files.deleteIfExists(p1.resolve("testfile1")));
System.out.println(Files.deleteIfExists(p2));
System.out.println(Files.deleteIfExists(p2));
System.out.println(Files.deleteIfExists(p2));
System.out.println(Files.deleteIfExists(p1));
System.out.println(Files.deleteIfExists(p1));
System.out.println(Files.deleteIfExists(p1));
}
}
}
catch
catch (IOException ex)
catch (IOException
(IOException ex)
ex)
{
{
{
System.out.println(ex);
System.out.println(ex);
System.out.println(ex);
}
}
}
}
}
}

The
The
Themethod
methodcreates
createsaaapath
pathp0
p0totomy
myhome
homedirectory.
directory.With
Withthis
thispath
pathavailable
availablemeans
means
The method
method creates
creates a path
path p0
p0 to
to my
my home
home directory.
directory. With
With this
this path
path available
available means
means
p0.resolve("testdir")
p0.resolve("testdir")
p0.resolve("testdir")

118
118
118
118
JAVA 5:
JAVA
JAVA 5: FILES
5: FILES AND
FILES AND JAVA
AND JAVA IO
JAVA IO
IO java.nIo
java.nio
java.nIo

the creation
the creation ofof aa path
path where
where the
the name
name testdir
testdir becomes
becomes aa file
file under
under p0 p0 in in this
this case
case aa
subdirectory. Files
subdirectory. Files has
has aa static
static method
method createDirrectory(),
createDirrectory(), whichwhich creates
creates aa directory
directory fromfrom aa
path and
path and returns
returns aa Path
Path object
object p1p1 to
to this
this directory.
directory. Likewise,
Likewise, p2 p2 isis aa path
path toto aa file
file inin this
this
directory. Files
directory. Files also
also has
has aa method
method copy()
copy() to to copy
copy aa file.
file. In
In this
this case,
case, thethe file
file that
that isis copied
copied
has the
has the path
path p2
p2 and
and isis copied
copied toto aa file
file in
in the
the same
same directory,
directory, butbut with
with the
the name
name testfile1.
testfile1.
The result
The result of
of performing
performing these
these statements
statements isis that
that in
in my
my home
home directory
directory isis created
created following
following
file tree:
file tree:

The last
The last three
three statements
statements of
of the
the method
method deletes
deletes this
this file
file tree
tree again,
again, and
and isis the
the method
method
executed, the
executed, the result
result is:
is:

/home/pa
/home/pa
/home/pa/testdir
/home/pa/testdir
/home/pa/testdir/testfile
/home/pa/testdir/testfile
true
true
true
true
true
true

The
The following
The following method
following method shows
method shows how
shows how to
how to create
to create aaa path
create path to
path to aaa file
to file in
file in my
in my tmp
my tmp directory,
tmp directory, and
directory, and then
and then
then
open
open an
open an OutputStream
an OutputStream with
OutputStream with this
with this path
this path and
path and prints
and prints 15
prints 15 bytes
15 bytes to
bytes to the
to the stream:
the stream:
stream:

private static
private static void
void test22()
test22()
{{
byte[] bb == {{ 2,
byte[] 2, 3,
3, 5,
5, 7,
7, 11,
11, 13,
13, 17,
17, 19,
19, 23,
23, 29,
29, 31,
31, 37,
37, 41,
41, 43,
43, 47
47 };
};
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file1");
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file1");
try (OutputStream
try (OutputStream out
out == Files.newOutputStream(path,
Files.newOutputStream(path, StandardOpenOption.CREATE))
StandardOpenOption.CREATE))
{{
out.write(b);
out.write(b);
}}
catch (IOException
catch (IOException ex)ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
}}

There isis not


There not much
much toto explain,
explain, but
but you
you should
should notice
notice how
how you
you can
can set
set an
an option
option to
to
newOutputStream(). StandardOpenOption
newOutputStream(). StandardOpenOption isis an
an enumeration,
enumeration, and
and you
you are
are encouraged
encouraged to
to
study the
study the other
other options.
options.

119
119
119
JAVA
JAVA 5:
JAVA 5: FILES
5: FILES AND
FILES AND JAVA
AND JAVA IO
JAVA IO
IO java.nIo
java.nIo
java.nio

This same
This same
This problem
same problem can
problem can also
can also be
also be solved
be solved as
solved as follows:
as follows:
follows:

private
private static
static void
void test23()
test23()
{
{
byte[] b
byte[] b == {{ 2,
2, 3,
3, 5,
5, 7,
7, 11,
11, 13,
13, 17,
17, 19,
19, 23,
23, 29,
29, 31,
31, 37,
37, 41,
41, 43,
43, 47
47 };
};
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file2");
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file2");
try
try
{
{
Files.write(path, b,
Files.write(path, b, StandardOpenOption.CREATE);
StandardOpenOption.CREATE);
}
}
catch (Exception
catch (Exception ex)ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

where
where the
where the method
the method write()
method write() opens
write() opens the
opens the file,
the file, writes
writes aaa byte
file, writes byte array
byte array to
array to the
to the file
the file and
file and close
close itit
and close again.
it again.
again.
Below
Below are
are two
two methods
methods that
that read
read the
the two
two files
files
Below are two methods that read the two files again:again:
again:

private
private static
static void
void test24()
test24()
{
{
byte[]
byte[] b
b =
= new
new byte[100];
byte[100];

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

120
120
120
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5:
JAVA 5: FILES
FILES AND
AND JAVA
JAVA IO
IO java.nIo
java.nIo

Path path
Path path =
= Paths.get(System.getProperty("user.home")).resolve("tmp/file1");
Paths.get(System.getProperty("user.home")).resolve("tmp/file1");
try
try (InputStream in
(InputStream in == Files.newInputStream(path))
Files.newInputStream(path))
{
{
int
int count
count == in.read(b);
in.read(b);
for (int
for (int i
i == 0;
0; ii << count;
count; ++i)
++i) System.out.print(b[i]
System.out.print(b[i] +
+ "
" ");
");
System.out.println();
System.out.println();
}
}
catch
catch (IOException
(IOException ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

private static
private static void
void test25()
test25()
{
{
Path path
Path path =
= Paths.get(System.getProperty("user.home")).resolve("tmp/file2");
Paths.get(System.getProperty("user.home")).resolve("tmp/file2");
try
try
{
{
byte[]
byte[] b b =
= Files.readAllBytes(path);
Files.readAllBytes(path);
for (int
for (int i
i == 0;
0; ii <
< b.length;
b.length; ++i)
++i) System.out.print(b[i]
System.out.print(b[i] +
+ "
" ");
");
System.out.println();
System.out.println();
}
}
catch
catch (Exception
(Exception ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

The next
The next method
method shows
shows how
how you
you with
with aa single
single statement
statement can
can write
write aa list
list of
of strings
strings to
to aa file:
file:

private static
private static void
void test26()
test26()
{
{
List<String> lines
List<String> lines == Arrays.asList("Gorm
Arrays.asList("Gorm den
den Gamle",
Gamle", "Harald
"Harald Bltand",
Bltand",
"Svend Tveskg", "Harald d. 2.", "Knud den Store", "Hardeknud",
"Svend Tveskg", "Harald d. 2.", "Knud den Store", "Hardeknud",
"Magnus den
"Magnus den Gode");
Gode");
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file3");
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file3");
try
try
{
{
Files.write(path, lines,
Files.write(path, lines, Charset.defaultCharset(),
Charset.defaultCharset(), StandardOpenOption.CREATE);
StandardOpenOption.CREATE);
}
}
catch (Exception
catch (Exception ex)
ex)
{
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}

121
121
121
JAVA
JAVA5:
JAVA 5:5:FILES
FILESAND
FILES ANDJAVA
AND JAVAIO
JAVA IO
IO java.nio
java.nIo
java.nIo

The
Themethod
The methodwrite(),
method write(),this
write(), thistime
this timehas
time hasfour
has fourparameters:
four parameters:
parameters:

write(Path path,
write(Path path, Iterable<?
Iterable<? extends
extends CharSequence>
CharSequence> lines,
lines, Charset
Charset cs,
cs,
OpenOption options)
OpenOption options)

wherethe
where thefirst
firstisisthe
thepath,
path,the
thenext
nextaacollection
collectionofofobjects
objectsderived
derivedfrom
fromCharSequence
CharSequence(and,
(and,
ininpractice
practiceititisisString),
String),the
thethird
thirdaacharacter
characterencoding
encodingand
andfinally
finallythe
thepossibility
possibilityofofmultiple
multiple
options.ItItisisvery
options. verysimple
simpletotocreate
createaatext
textfile.
file.

Belowisisaamethod
Below methodthat
thatreads
readsthe
thefile
fileagain:
again:

private static
private static void
void test27()
test27()
{{
Path path
Path path == Paths.get(System.getProperty("user.home")).resolve("tmp/file3");
Paths.get(System.getProperty("user.home")).resolve("tmp/file3");
try
try
{{
List<String> list
List<String> list == Files.readAllLines(path,
Files.readAllLines(path, Charset.defaultCharset());
Charset.defaultCharset());
for (String
for (String line
line :: list)
list) System.out.println(line);
System.out.println(line);
}}
catch (Exception
catch (Exception ex)
ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
}}

Gorm den
Gorm den Gamle
Gamle
Harald Bltand
Harald Bltand
Svend Tveskg
Svend Tveskg
Harald d.
Harald d. 2.
2.
Knud den
Knud den Store
Store
Hardeknud
Hardeknud
Magnus den
Magnus den Gode
Gode

The
Thefollowing
The followingmethods
following methodsshows
methods showsthe
shows thesame,
the same,but
same, butinstead
but insteadthey
instead theyuses
they usesrespectively
uses respectivelyaaaBufferedWriter
respectively BufferedWriter
BufferedWriter
and
andaaaBufferedReader,
and BufferedReader,and
BufferedReader, andalso
and alsoare
also areshown
are shownhow
shown howyou
how youcan
you canspecify
can specifythe
specify theencoding:
the encoding:
encoding:

private static
private static void
void test28()
test28()
{{
List<String> lines
List<String> lines == Arrays.asList("Gorm
Arrays.asList("Gorm den
den Gamle",
Gamle", "Harald
"Harald Bltand",
Bltand",
"Svend Tveskg",
"Svend Tveskg", "Harald
"Harald d.
d. 2.",
2.", "Knud
"Knud den
den Store",
Store", "Hardeknud",
"Hardeknud",
"Magnus den
"Magnus den Gode");
Gode");
Path path
Path path == Paths.get(System.getProperty("user.home")).resolve("tmp/file4");
Paths.get(System.getProperty("user.home")).resolve("tmp/file4");
try (BufferedWriter
try (BufferedWriter writer
writer ==
Files.newBufferedWriter(path, Charset.availableCharsets().get("UTF-8")))
Files.newBufferedWriter(path, Charset.availableCharsets().get("UTF-8")))
{{

122
122
122
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo

for (String line : lines)


{
writer.write(line);
writer.newLine();
}
}
catch (IOException ex)
{
System.out.println(ex);
}
}

private static void test29()


{
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file4");
try (BufferedReader reader =
Files.newBufferedReader(path, Charset.availableCharsets().get("UTF-8")))
{
for (String line = reader.readLine(); line != null; line = reader.readLine())
System.out.println(line);
}
catch (IOException ex)
{

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

123
123
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo

System.out.println(ex);
}
}

The most important of these examples is how you with the class Files can create both a
BufferedWriter and a BufferedReader.

The next two examples are similar and shows how the class Files can create a BufferedOutputStream
and a BufferedInputStream:

private static void test30()


{
byte data[] = new byte[100];
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file5");
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(
path, StandardOpenOption.CREATE, StandardOpenOption.APPEND)))
{
rand.nextBytes(data);
for (int i = 0; i < 100; ++i) out.write(data);
}
catch (IOException ex)
{
System.out.println(ex);
}
}

private static void test31()


{
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file5");
long sum = 0;
try (InputStream in = new BufferedInputStream(Files.newInputStream(path)))
{
for (int t = in.read(); t != -1; t = in.read()) sum += t;
}
catch (IOException ex)
{
System.out.println(ex);
}
System.out.println(sum);
}

The first method writes 10000 bytes to a BufferedOutputStream, and here you should especially
The first method writes 10000 bytes to a BufferedOutputStream, and here you should especially
note that it is opened in append mode. The method writes 100 times, and each time it
note that it is opened in append mode. The method writes 100 times, and each time it
writes an array with 100 random bytes. The last method reads the file again by means of
writes an array with 100 random bytes. The last method reads the file again by means of
a BufferedInputStream and determines the sum.
a BufferedInputStream and determines the sum.

124
124
JAVA
JAVA 5:
JAVA 5: FILES
5: FILES AND
FILES AND JAVA
AND JAVA IO
JAVA IO
IO java.nIo
java.nio
java.nIo

As
As the
the last
last example
example II will
will show
show how
how to
to write
write strings
strings to
to aa file,
file, but
but this
this time
time by
by using
using aa channel:
channel:

private
private static
static void
void test32()
test32()
{{
List<String>
List<String> lines
lines == Arrays.asList("Gorm
Arrays.asList("Gorm denden Gamle",
Gamle", "Harald
"Harald Bltand",
Bltand",
"Svend Tveskg", "Harald d. 2.", "Knud den Store", "Hardeknud",
"Svend Tveskg", "Harald d. 2.", "Knud den Store", "Hardeknud",
"Magnus
"Magnus den
den Gode");
Gode");
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file6");
Path path = Paths.get(System.getProperty("user.home")).resolve("tmp/file6");
try
try (ByteChannel
(ByteChannel channel
channel == Files.newByteChannel(path,
Files.newByteChannel(path,
StandardOpenOption.CREATE,
StandardOpenOption.CREATE, StandardOpenOption.WRITE))
StandardOpenOption.WRITE))
{{
for
for (String
(String line
line :: lines)
lines)
{{
ByteBuffer
ByteBuffer buffer
buffer ==
ByteBuffer.wrap((line
ByteBuffer.wrap((line ++ \n').getBytes(Charset.forName("UTF-8")));
\n').getBytes(Charset.forName("UTF-8")));
channel.write(buffer);
channel.write(buffer);
}}
}}
catch
catch (IOException
(IOException ex)
ex)
{{
System.out.println(ex);
System.out.println(ex);
}}
}}

First
First isis created
created aa list
list with
with the
the names
names of of the
the same
same 77 Danish
Danish kings
kings as as used
used above
above and
and then
then aa
path
path toto aa file
file in
in my
my tmp
tmp directory
directory isis created.
created. TheThe class
class Files
Files has
has aa method
method newByteChannel(),
newByteChannel(),
which
which creates
creates aa ByteChannel
ByteChannel forfor aa file
file identified
identified by by aa path.
path. With
With this
this channel
channel ready
ready the
the
method
method performs
performs aa looploop that
that iterates
iterates over
over all
all strings
strings inin the
the list.
list. For
For each
each string
string (name)
(name) are
are
added a line break, and all are converted to a byte array after
added a line break, and all are converted to a byte array after an UTF-8 encoding. This an UTF-8 encoding. This
array
array isis finally
finally encapsulated
encapsulated inin aa ByteBuffer
ByteBuffer that
that isis send
send out
out onon the
the channel.
channel.

Below
Below isis the
the equivalent
equivalent method,
method, which
which reads
reads the
the file
file again:
again:

private
private static
static void
void test33()
test33()
{{
Path
Path path
path == Paths.get(System.getProperty("user.home")).resolve("tmp/file6");
Paths.get(System.getProperty("user.home")).resolve("tmp/file6");
try
try (ByteChannel channel
(ByteChannel channel == Files.newByteChannel(path,
Files.newByteChannel(path, StandardOpenOption.READ))
StandardOpenOption.READ))
{{
ByteBuffer
ByteBuffer buffer
buffer == ByteBuffer.allocate(30);
ByteBuffer.allocate(30);
while
while (channel.read(buffer)
(channel.read(buffer) >> 0) 0)
{{
buffer.flip();
buffer.flip();
System.out.print(Charset.forName("UTF-8").decode(buffer));
System.out.print(Charset.forName("UTF-8").decode(buffer));
buffer.clear();
buffer.clear();
}}

125
125
125
JAVA 5: FILES AND JAVA IO java.nio
JAVA 5: FILES AND JAVA IO java.nIo

System.out.println();
}
catch (IOException ex)
{
System.out.println(ex);
}
}

There is
There is again
again created
created aa ByteChannel
ByteChannel to to the
the file,
file, and
and then
then aa ByteBuffer.
ByteBuffer. The
The number
number 30 30 isis
arbitrary, but
arbitrary, but is,
is, however,
however, selected
selected so
so that
that the
the buffer
buffer is
is not
not large
large enough
enough toto contain
contain the
the
longest name.
longest name. More
More precisely,
precisely, this
this means
means thatthat the
the subsequent
subsequent readread on
on the
the channel
channel reads
reads
the 30
the 30 bytes
bytes at
at aa time
time until
until there
there is
is fewer
fewer than
than 30 30 bytes.
bytes. Every
Every time
time the
the buffer
buffer is
is full,
full, or
or
more exactly
more exactly when
when thethe read()
read() method
method is is performed
performed the the program
program executes
executes aa flip()
flip() and
and the
the
byte content
byte content ofof the
the buffer
buffer is
is decoded
decoded to to aa String,
String, which
which isis printed
printed on
on the
the screen.
screen.

360
thinking .

360
thinking . 360
thinking .
Discover the truth at www.deloitte.ca/careers Dis

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


126
126
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Operations
operatIons on
on simple
sImple data
data types
types

4 
4 OPERATIONS
OPERATIONS ON
ON SIMPLE
SIMPLE
DATA
DATA TYPES
TYPES
Any
Any data
data element
element (simple
(simple variable
variable or
or object)
object) uses
uses space
space in
in the
the machines
machines memory,
memory, and and when
when
the
the smallest
smallest addressable
addressable unitunit in
in the
the machines
machines memory
memory isis aa byte,
byte, uses
uses all all data
data elements
elements
without
without exception
exception aa whole
whole number
number of of bytes.
bytes. What
What itit isis depends
depends on on the the element
element andand isis
determined
determined by by the
the elements
elements data
data type.
type. AA byte
byte consists
consists of
of 88 bits
bits (that
(that isis 88 of
of the
the symbols
symbols 00
and
and 1),
1), and
and thus
thus you
you cancan consider
consider aa byte
byte as
as aa bit
bit pattern
pattern consisting
consisting of of 88 bits.
bits. Since
Since aa bit
bit
can
can take
take onon two
two values,
values, aa byte
byte thus
thus can
can represent
represent different
different values.
values. HowHow thesethese values
values are
are
interpreted
interpreted depends
depends entirely
entirely on
on the
the program
program andand thethe data
data elements
elements data
data types,
types, and
and in
in some
some
contexts
contexts itit will
will be
be as
as aa number,
number, while
while in
in other
other contexts
contexts would
would be be aa code
code for for aa character.
character.

In
In this
this chapter
chapter II will
will in
in detail
detail describe
describe how
how thethe simple
simple data
data types
types are
are represented
represented inin Java
Java as
as
bit
bitpatterns
patternsand
andin inthis
thiscontext
contextalso
alsowhat
whatoperations
operationsare areavailable
availableto
tomanipulate
manipulatethe theindividual
individual
bits.
bits. The
The chapter
chapter assumes
assumes knowledge
knowledge of of the
the binary
binary numbers,
numbers, andand also
also the
the hexadecimal
hexadecimal
numbers,
numbers, andand so
so far
far you
you lack
lack the
the knowledge
knowledge referring
referring to
to the
the books
books appendix.
appendix.

4.1
4.1 THE
THE INTEGERS
INTEGERS
Java
Java has
has asas already
already described
described fourfour types
types ofof integers:
integers: byte,
byte, short,
short, int
int and
and long,
long, and
and they
they differ
differ
only
only with
with respect
respect toto what
what they
they fill
fill in
in memory,
memory, which which areare respectively
respectively 1, 1, 2,
2, 44 oror 88 bytes.
bytes.
As
As anan example
example an an int
int uses
uses 44 bytes,
bytes, andand isis in
in memory
memory allocated
allocated as as 44 contiguous
contiguous bytes.
bytes. This
This
means
means thatthat anan int
int uses
uses 32 32 bits
bits and
and cancan therefore
therefore represent
represent 4294967296
4294967296 different
different integers
integers
as
as there
there with
with 32 32 bits
bits isis 4294967296
4294967296 different
different bitbit patterns
patterns (2 (2 ).). The
32
32
The 32 32 bits
bits are
are interpreted
interpreted
as
as aa binary
binary number,
number, and and where
where negative
negative numbers
numbers are are represented
represented by by their
their 22 complement.
complement.
This
This corresponds
corresponds to, to, that
that anan int
int represents
represents the the integers
integers in
in the
the range
range [a,[a, b]
b] where
where

a = -2147483648 (the binary number 10000000000000000000000000000000)


b = 2147483647 ( the binary number 01111111111111111111111111111111)

Any integer type supports the binary operations:


Any integer type supports the binary operations:

-- | bitvis or
- | bitvis or
-- & bitvis and
- & bitvis and
-- ^ bitvis xor
- ^ bitvis xor
-- ~ 1 complement or just complement
- ~ 1 complement or just complement
-- << left shift
- << left shift
-- >> arithmetic right shift
- >> arithmetic right shift
-- >>> right shift
- >>> right shift

127
127
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Operations
operatIons on
operatIons on simple
sImple data
sImple data types
types

The
The representation
representation of
of integers
integers isis simple,
simple, and
and itit isis easy
easy test
test the
the above
above in
in Java.
Java. The
The program
program
BinProgram
BinProgram contains
contains the
the following
following method:
method:

public static
public static String
String toBin(int
toBin(int t)t)
{{
StringBuilder builder
StringBuilder builder == new
new StringBuilder();
StringBuilder();
for (int
for (int ii == 0;
0; ii << 32;
32; ++i,
++i, tt <<=
<<= 1)
1)
builder.append((t && 0x80000000)
builder.append((t 0x80000000) ==== 00 ?? 0'
0' :: 1');
1');
return builder.toString();
return builder.toString();
}}

that converts
that converts an
an integer
integer to
to aa 32-bit
32-bit string.
string. Note
Note that
that the
the class
class Integer
Integer has
has aa method
method
toBinaryString(), which
toBinaryString(), which returns
returns an
an int
int as
as aa bit
bit string,
string, but
but the
the method
method does
does not
not preceds
preceds by
by
0s, so
0s, so the
the above
above method.
method. IfIf you
you perform
perform the the following
following method
method

private static
private static void
void test01()
test01()
{{
print(113);
print(113);
print(-113);
print(-113);
print(0);
print(0);
print(-1);
print(-1);
print(Integer.MAX_VALUE);
print(Integer.MAX_VALUE);
print(Integer.MIN_VALUE);
print(Integer.MIN_VALUE);
}}

private static
private static void
void print(int
print(int t)
t)
{{
System.out.println(toBin(t) ++ "" == "" ++ t);
System.out.println(toBin(t) t);
}}

you get
you get the
the result
result

00000000000000000000000001110001
00000000000000000000000001110001 == 113
113
11111111111111111111111110001111
11111111111111111111111110001111 == -113
-113
00000000000000000000000000000000
00000000000000000000000000000000 == 00
11111111111111111111111111111111
11111111111111111111111111111111 == -1
-1
01111111111111111111111111111111
01111111111111111111111111111111 == 2147483647
2147483647
10000000000000000000000000000000
10000000000000000000000000000000 == -2147483648
-2147483648

corresponding to
corresponding to what
what isis said
said above.
above. Likewise
Likewise the
the method:
method:

private static
private static void
void test02()
test02()
{{
int aa == 0xF0F0F0F0;
int 0xF0F0F0F0;
int bb == 0x3C3C3C3C;
int 0x3C3C3C3C;
System.out.println(toBin(a));
System.out.println(toBin(a));

128
128
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

System.out.println(toBin(b));
System.out.println(toBin(a | b));
System.out.println(toBin(a & b));
System.out.println(toBin(a ^ b));
System.out.println(toBin(~a));
System.out.println(toBin(a << 3));
System.out.println(toBin(a >> 3));
System.out.println(toBin(a >>> 3));
}

results in the following:

11110000111100001111000011110000
00111100001111000011110000111100
11111100111111001111110011111100
00110000001100000011000000110000
11001100110011001100110011001100
00001111000011110000111100001111
10000111100001111000011110000000
11111110000111100001111000011110
00011110000111100001111000011110

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

129
129
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO Operations
operatIonson
onsimple
sImpledata
datatypes
types

Here
Here you you should
should specifically
specifically note
note that
that thethe two
two variables
variables aa and
and bb are
are initialized
initialized using
using
hexadecimal
hexadecimal valuesvalues that
that are
are useful
useful when
when working
working with
with binary
binary integers.
integers. Note
Note also
also that
that the
the
operator
operator>> >>isisananarithmetic
arithmeticright
rightshift
shift(is(isthe
thesign
signbit
bitwhich
whichisisadded),
added),but
butthe
the>>>
>>>operator
operator
isis aa right
right shift,
shift, that
that always
always inserts
inserts aa 0.0.

As
As for
for the
the other
other types
types to
to integers
integers itit isis only
only the
the ranges,
ranges, that
that the
the types
types represents
represents that
that are
are
different,
different, and
and therefore
therefore howhow big
big numbers
numbers to to work
work with.
with. However,
However, the the binary
binary operations
operations
sometimes
sometimesgive giveaadifferent
differentresult
resultthan
thanexpected.
expected.IfIfan anargument
argumentisisaabyte
byteor orshort,
short,the
theargument
argument
will
willbebeconverted
convertedto toan
anint
intbefore
beforethe
theoperation
operationisisperformed
performedand andthetheresult
resultwill
willbe
beaa3232bit
bit
int.
int.IfIfthe
theargument
argumentrepresents
representsaanegative
negativenumbernumberititmaymayresult
resultininaadifferent
differentoutcome
outcomethan
than
expected.
expected. Something
Something similar
similar may
may happen
happen ifif an an argument
argument isis aa long
long asas the
the second
second argument
argument
then
thenmust
mustbe beconverted
convertedto toaalong
longbefore
beforethe theoperation
operationisisperformed.
performed.Consider
Considerasasan anexample
example
the
the following
following method:
method:

private static void test03()


{
byte b = -56;
byte b1 = (byte)(b >> 3);
byte b2 = (byte)(b >>> 3);
byte b3 = (byte)((b & 0xff) >>> 3);
System.out.println(toBin(b));
System.out.println(toBin(b1));
System.out.println(toBin(b2));
System.out.println(toBin(b3));
}

IfIf the
the method
method isis performed,
performed, you
you get
get the
the result:
result:

11111111111111111111111111001000
11111111111111111111111111111001
11111111111111111111111111111001
00000000000000000000000000011001

The value
The value ofof bb isis 11001000,
11001000, and and when
when itit isis transferred
transferred to to tobin(),
tobin(), itit will
will bebe expanded
expanded
toto 32
32 bits
bits and
and areare filled
filled with
with the the sign.
sign. The
The first
first result
result isis asas expected.
expected. This
This also
also applies
applies toto
the second
the second result
result when
when itit isis an
an arithmetic
arithmetic shift,
shift, butbut you
you should
should note
note that
that the
the operation
operation
isis performed
performed by by first
first expanding
expanding bb to to 32
32 bits
bits andand then
then performs
performs an an arithmetic
arithmetic shift.
shift. The
The
third result
third result isis however
however not not what
what oneone would
would expect,
expect, since
since itit isis aa non
non arithmetic
arithmetic shift,
shift, but
but
the following
the following occur:
occur:

130
130
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Operations
operatIons on
on simple
sImple data
data types
types

bb isis expanded
expanded to to 32
32 bits:
bits: 11111111111111111111111111001000
11111111111111111111111111001000
aa right
right shift
shift on
on 33 bits:
bits: 00011111111111111111111111111001
00011111111111111111111111111001
aa type
type cast
cast to
to aa byte: 11111001
byte: 11111001
expanded
expanded to to 32
32 bits
bits with
with aa call
call to
to toBin(): 11111111111111111111111111111001
toBin(): 11111111111111111111111111111001

The
The problem
problem can
can be
be solved
solved by
by expanded
expanded bb to
to 32
32 bits:
bits:

b && 0xff =
11111111111111111111111111001000 & 00000000000000000000000011111111 =
00000000000000000000000011001000

EXERCISE
EXERCISE 66
Add
Add aa class
class named
named Binary
Binary toto the
the class
class library
library PaLib
PaLib when
when the
the class
class must
must be
be part
part of
of the
the
package
package palib.util.
palib.util. The
The class
class must
must have
have the
the following
following methods:
methods:

package palib.util;

public class Binary


{
/**
* Converts the argument to a binary string of 8 bits.
* @param b The byte to be converted
* @return The argument converted to a binary string of 8 bits
*/
public static String toBin(byte b) { }

/**
* Converts the argument to a binary string of 16 bits.
* @param t The integer to be converted
* @return The argument converted to a binary string of 16 bits
*/
public static String toBin(short t) { }

/**
* Converts the argument to a binary string of 32 bits.
* @param t The integer to be converted
* @return The argument converted to a binary string of 32 bits
*/
public static String toBin(int t) { }

131
131
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

/**
* Converts the argument to a binary string of 64 bits.
* @param t The integer to be converted
* @return The argument converted to a binary string of 64 bits
*/
public static String toBin(long t) { }

/**
* Converts the argument to a binary string of 16 bits.
* @param t The integer to be converted
* @param c Seperation character between byte values
* @return The argument converted to a binary string of 16 bits
*/
public static String toBin(short t, char c) { }

/**
* Converts the argument to a binary string of 32 bits.
* @param t The integer to be converted
* @param c Seperation character between byte values
* @return The argument converted to a binary string of 32 bits
*/
public static String toBin(int t, char c) { }

e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili www.discovermitas.com
Maersk.com/Mitas e G
I joined MITAS because for Engine
I wanted real responsibili Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
ree wo
work
or placements ssolve pr

132
132
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

/**
* Converts the argument to a binary string of 64 bits.
* @param t The integer to be converted
* @param c Seperation character between byte values
* @return The argument converted to a binary string of 64 bits
*/
public static String toBin(long t, char c) { }
}

Also,
Also, write
write aa program
program that
that can
can test
test the
the methods
methods in
in the
the new
new class.
class.

Java
Java supports
supports as
as mentioned
mentioned above,
above, the
the binary
binary operations,
operations, including
including in
in particular
particular the
the left
left
and right shift. As other binary operations are rotations. If, for example
and right shift. As other binary operations are rotations. If, for example

bb == 11001000
11001000

is
is

b = 00110010

aa binary
binary right
right rotation
rotation on
on 2,
2, while
while

b = 00100011

is
is aa binary
binary left
left rotation
rotation on
on 2.
2. You
You must
must now
now expand
expand the
the class
class Binary
Binary with
with the
the following
following
methods:
methods:

/**
* Rotates the argument b n bits to the right.
* @param b The argument to be rotated
* @param n The number of bits to be rotated
* @return The argument b rotated n bits to the right
*/
public static byte ror(byte b, int n) { }

/**
* Rotates the argument t n bits to the right.
* @param t The argument to be rotated
* @param n The number of bits to be rotated
* @return The argument t rotated n bits to the right
*/
public static short ror(short t, int n) { }

133
133
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

/**
* Rotates the argument t n bits to the right.
* @param t The argument to be rotated
* @param n The number of bits to be rotated
* @return The argument t rotated n bits to the right
*/
public static int ror(int t, int n) { }

/**
* Rotates the argument t n bits to the right.
* @param t The argument to be rotated
* @param n The number of bits to be rotated
* @return The argument t rotated n bits to the right
*/
public static long ror(long t, int n) { }

/**
* Rotates the argument b n bits to the left.
* @param b The argument to be rotated
* @param n The number of bits to be rotated
* @return The argument b rotated n bits to the left
*/
public static byte rol(byte b, int n) { }

/**
* Rotates the argument b n bits to the left.
* @param t The argument to be rotated
* @param n The number of bits to be rotated
* @return The argument b rotated n bits to the left
*/
public static short rol(short t, int n) { }

/**
* Rotates the argument b n bits to the left.
* @param t The argument to be rotated
* @param n The number of bits to be rotated
* @return The argument b rotated n bits to the left
*/
public static int rol(int t, int n) { }

/**
* Rotates the argument b n bits to the left.
* @param t The argument to be rotated
* @param n The number of bits to be rotated
* @return The argument b rotated n bits to the left
*/
public static long rol(long t, int n) { }

You
Youalso
alsoyou
youneed
needtotoexpand
expandthe
thetest
testprogram
programtototest
testthe
themethods
methodsfor
forbinary
binaryrotation.
rotation.

134
134
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO Operations
operatIonson
onsimple
sImpledata
datatypes
types

EXERCISE
EXERCISE77
Java
Javadefines
definesaaclass
classcalled
calledBitSet
BitSetand
andwhich,
which,ininprinciple,
principle,represents
representsaaset,
set,but
butasasaaso-called
so-called
bitmap,
bitmap,which
whichcancanbe
bethought
thoughtofofasasan
anarray
arrayconsisting
consistingofofelements
elementsofofthe
thetype
typebits,
bits,and
andthus
thus
elements
elementsthat
thatare
are0,0,or
or1.1.You
Youmust
mustininthis
thisexercise
exercisewrite
writeaaprogram
programnamed
namedBitmapProgram
BitmapProgram
that has three test methods for the class BitSet.
that has three test methods for the class BitSet.

The
The first
first method
method must
must create
create aa BitSet
BitSet and
and tests
tests the
the methods
methods size(),
size(), cardinality(),
cardinality(), set()
set() and
and
toString().
toString().

Add
Addaamethod
method

static String toBin(BitSet s)


{
}

that
thatreturns
returnsaabit
bitstring
stringfor
forthe
theBitSet
BitSets.s.

135
135
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Operations
operatIons on
on simple
sImple data
data types
types

You
You must
must then
then write
write aa second
second test
test method,
method, when
when the
the method
method must
must create
create aa BitSet
BitSet with
with
the
the values 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29, and then the method must print the
values 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29, and then the method must print the
corresponding bit string by means of the above toBin( ) method.
corresponding bit string by means of the above toBin( ) method.

Write
Write finally
finally aa test
test method
method that
that creates
creates two
two BitSet
BitSet objects
objects initialized
initialized with
with appropriate
appropriate values.
values.
The test method should then try the BitSet classs and(), notAnd(), or() and xor()
The test method should then try the BitSet classs and(), notAnd(), or() and xor() methods. methods.

PROBLEM
PROBLEM 33
AA BitSet
BitSet isis an
an example
example of
of aa bitmap,
bitmap, and
and in
in this
this problem
problem you
you should
should write
write aa class
class Bitmap
Bitmap
that represents a bitmap and is an alternative to the Javas BitSet. A bitmap is, in
that represents a bitmap and is an alternative to the Javas BitSet. A bitmap is, in principle,principle,
aa sequence
sequence of of bits:
bits:

0010111010101010101011110101010100111111101010101011111000100001

where there
where there isis 64
64 bits.
bits. Such
Such aa bitmap
bitmap can,
can, for
for example
example bebe implemented
implemented as as eight
eight bytes,
bytes, 22
ints or
ints or aa long.
long. AA bitmap
bitmap must,
must, however,
however, bebe more
more general
general and
and should
should bebe able
able to
to be
be of
of any
any
size, and
size, and therefore
therefore itit should
should be
be implemented
implemented as as an
an array
array of
of one
one ofof the
the simple
simple types
types to
to
integers. Immediately
integers. Immediately itit isis simple
simple to
to implement
implement aa bitmap,
bitmap, but
but there
there are
are several
several things
things you
you
must consider
must consider andand make
make aa decision.
decision. As
As important
important examples
examples II will
will mention:
mention:

--- which
which type
type to
to be
be used
used to
to the
the internal
internal array
array for
for the
the individual
individual bits
bits
--- must
must the
the bitmap
bitmap have
have fixed
fixed size
size
--- which
which sizes
sizes should
should be
be possible
possible forfor aa bitmap
bitmap andand should
should itit be
be aa multiplum
multiplum of
of the
the
size of
size of the
the arrays
arrays elements
elements
--- which
which operations
operations must
must aa bitmap
bitmap make
make available
available
--- when
when areare two
two bitmaps
bitmaps compatible
compatible

As regards
As regards of
of the
the first,
first, you
you can
can choose
choose between
between byte,
byte, short,
short, int
int and
and long.
long. In
In the
the case
case of
of aa
large bitmap,
large bitmap, you
you should
should select
select aa type
type with
with many
many bits
bits as
as itit means
means aa smaller
smaller array,
array, and
and thus
thus
shorter loops
shorter loops in
in the
the methods,
methods, providing
providing increased
increased efficiency.
efficiency. InIn the
the case
case of
of small
small bitmaps,
bitmaps,
aa 64
64 bits
bits element
element can can means
means unnecessary
unnecessary space
space consumption,
consumption, but but inin most
most practical
practical cases
cases
where you
where you need
need aa bitmap,
bitmap, itit will
will bebe bitmaps
bitmaps with
with many
many bits,bits, and
and itit indicates
indicates to
to choose
choose aa
type with
type with room
room for
for many
many bits.
bits. Below
Below youyou should
should select
select the
the type
type long.
long.

As for
As for the
the size,
size, itit isis the
the application
application that
that determines
determines whatwhat isis the
the best
best choice.
choice. In In this
this task,
task,
the size
the size must
must bebe fixed,
fixed, where
where you
you have
have toto specify
specify the
the size
size as
as aa parameter
parameter to to the
the constructor.
constructor.
ItIt must
must be be able
able to to have
have any
any logical
logical size
size for
for example
example 70 70 bits.
bits. IfIf itit isis implemented
implemented as as an
an
array of
array of the
the type
type long
long itit will
will occupies
occupies 128
128 bits,
bits, but
but there
there should
should onlyonly be be access
access (reference)
(reference)
to the
to the first
first 70.
70.

136
136
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Operations
operatIons on
on simple
sImple data
data types
types

Based
Based on
on the
the above,
above, itit is
is your
your task
task to
to expand
expand the
the class
class library
library PaLib
PaLib with
with the
the following
following class:
class:

package palib.util;

import java.util.*;

/**
* Implements a bitmap consisting of an arbitrary number of bits.
* The number of bits (size) is fixed and defined when creating an object.
* Two bitmaps are compatible only if they consist of the same number of bits.
*/
public class Bitmap implements Comparable<Bitmap>

{
/**
* Creates a bitmap of size bits. All bits is 0.
* @param size The size of the bitmap
*/
public Bitmap(int size) { }

/**
* Creates a bitmap initialized with a BitSet. The size is determined by the
* logic value of s, and the individual bits are initialized corresponding to
* the elements of s.
* @param s The BitSet, to initialize this bitmap
*/
public Bitmap(BitSet s) { }

/**
* Creates a bitmap, which is initialized with a byte array.
* @param arr The array used to initialize this bitmap
*/
public Bitmap(byte[] arr) { }

/**
* Copy constructor.
* @param bm The bitmap, that must be copied
*/
public Bitmap(Bitmap bm) { }

/**
* Returns the size of this bitmap
* @return The size of this bitmap
*/
public int getSize() { }

137
137
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

/**
* Returns where the n'th bit is 1.
* @param n Index of the bit to be tested
* @return true, if the n'th bit is 1
*/
public boolean get(int n) { }

/**
* Sets the n'th bit in the bitmap to 1 or 0. Sets the n'th bit to 1 if the value
* is true and 0 otherwise.
* @param n Index of the bit to be set
* @param value true means 1 and false 0
*/
public void set(int n, boolean value) { }

/**
* Sets all bits to 0.
*/
public void clear() { }

BUSINESS HAPPENS HERE.


www.fuqua.duke.edu/globalmba

138
138
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

/**
* Swap all bits in this bitmap.
* @return A reference to the current bitmap
*/
public Bitmap flip() { }

/**
* Performs an AND between the bitmap and the parameter.
* The result is that the state of this bitmap is changed.
* @param bm The bitmap that this bitmap are AND'ed with
* @return A reference to the current bitmap
* @throws UtilException If the two bitmaps are different lengths
*/
public Bitmap and(Bitmap bm) throws UtilException { }

/**
* Performs an OR between the bitmap and the parameter.
* The result is that the state of this bitmap is changed.
* @param bm The bitmap that this bitmap are OR'ed with
* @return A reference to the current bitmap
* @throws UtilException If the two bitmaps are different lengths
*/
public Bitmap or(Bitmap bm) throws UtilException { }

/**
* Performs an XOR between the bitmap and the parameter.
* The result is that the state of this bitmap is changed.
* @param bm The bitmap that this bitmap are XOR'ed with
* @return A reference to the current bitmap
* @throws UtilException If the two bitmaps are different lengths
*/
public Bitmap xor(Bitmap bm) throws UtilException { }

/**
* Performs a left shift on the current bitmap on n bits
* @param n The number of bits to shift
* @return A reference to the current bitmap
*/
public Bitmap shl(int n) { }

/**
* Performs a right shift on the current bitmap on n bits.
* It is a non-arithmetic shift.
* @param n The number of bits to shift
* @return A reference to the current bitmap
*/
public Bitmap shr(int n) { }

139
139
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

/**
* Performing a comparison of the current bitmap by parameter bm. The first bit,
* where the two bitmaps are different, determines the order, so that 1
* is considered high.
* @param bm The bitmap to be compared with
* @return 1 if the current bitmap is the largest, -1 if it is less than,
* and 0 if there are the same
*/
@Override
public int compareTo(Bitmap bm) { }

/**
* Overriding toString() so that it returns a string of the bits in the bitmap
* @return A bit string representing the bits in the bitmap
*/
@Override
public String toString() { }

/**
* Overloading of equals().
* @param obj The object to be compared with
* @return true, if the current bitmap is the same value as the obj interpreted
* as a bitmap
*/
@Override
public boolean equals(Object obj) { }

/**
* Overriding hash code, which is done by performers an xor of this bitmaps 32
* bit words.
* @return A hash code for this bitmap
*/
@Override
public int hashCode() { }

/**
* Returns the value of this bitmap as a BitSet.
* @return The value of this bitmap as a BitSet.
*/
public BitSet toBitSet() { }
/**

* Returns this bitmap as a byte array. If the length of the bitmap do not
* specify an exact number of bytes the last byte id filled with 0 bits.
* @return This bitmap as a byte array
*/
public byte[] toBytes() { }

140
140
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

/**
* Static method returns a bitmap, which is a copy of the parameter bm, but with
* all the bits inverted.
* @param bm The bitmap to be returned a flip of
* @return A flip of the parameter bm
*/
public static Bitmap flip(Bitmap bm) { }

/**
* Static method returns a bitmap, that is an AND of the bm1 and bm2.
* @param bm1 The first argument to the binary operation
* @param bm2 The second argument to the binary operation
* @return An and of bm1 and bm2
* @throws UtilException If the two bitmaps are of different length
*/
public static Bitmap and(Bitmap bm1, Bitmap bm2) throws UtilException { }

Excellent Economics and Business programmes at:

The perfect start


of a successful,
international career.

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

141
141
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

/**
* Static method returns a bitmap, that is an OR of the bm1 and bm2.
* @param bm1 The first argument to the binary operation
* @param bm2 The second argument to the binary operation
* @return An or of bm1 and bm2
* @throws UtilException If the two bitmaps are of different length
*/
public static Bitmap or(Bitmap bm1, Bitmap bm2) throws UtilException { }

/**
* Static method returns a bitmap, that is a XOR of the bm1 and bm2.
* @param bm1 The first argument to the binary operation
* @param bm2 The second argument to the binary operation
* @return A xor of bm1 and bm2
* @throws UtilException If the two bitmaps are of different length
*/
public static Bitmap xor(Bitmap bm1, Bitmap bm2) throws UtilException { }

/**
* Static method returns a bitmap, which is a copy of the parameter bm shifted n
* places to the left.
* @param bm The bitmap that is copied and changed
* @param n The number of bits to be shifted
* @return A copy of bm shifted n places to the left
*/
public static Bitmap shl(Bitmap bm, int n) { }

/**
* Static method returns a bitmap, which is a copy of the parameter bm shifted n
* places to the right. It is a non-arithmetic shift.
* @param bm The bitmap that is copied and changed
* @param n The number of bits to be shifted
* @return A copy of bm shifted n places to the right
*/
public static Bitmap shr(Bitmap bm, int n) { }
}

You should also expand the class Binary with a new method:
You should also expand the class Binary with a new method:
/**
/** * Converts a bitmap to a binary string where the individual bytes are separated
* Converts a bitmap c.to a binary string where the individual bytes are separated
* by the character
* by the character
* @param bm Thec. bitmap to be converted
* @param
* @parambmc Seperation
The bitmapcharacter
to be converted
between byte values
* @param
* @return bm converted to a bit string byte values
c Seperation character between
* @return bm converted to a bit string

142
142
JAVA 5: FILES AND JAVA IO Operations on simple data types

*/
public static String toBin(Bitmap bm, char c)
{
}

When you have written the class (and the above methods), you must write a test program
(for example TestBitmap) that can test the class.

PROBLEM 4
As an example of using a bitmap, you must write a program that uses Eratostheness algorithm
to determine the primes. The idea is the following:

In order to determine all prime numbers that are less than or equal to N, start by defining
a bitmap with N+1 elements:

In the beginning all positions are 0. You then starts with putting a mark (a 1 bit) in position
0 and position 1 as well as all the positions where the index is divisible by 2 though not
position 2:

In this run has been set a mark in all the even numbers greather than 2, as they are not
primes. You then repeats it all, but this time you put a mark on the positions where the
index is divisible by 3 though not position 3:

All positions where the index has 3 as the prime factor is now marked. Next time you
repeat it all with the number 5 (the first position after 3 that is 0). All positions where the
index has 5 as the prime factor is marked:

143
JAVA 5: FILES AND JAVA IO Operations on simple data types

To resume. Next time start with the first position, which is not marked (it is position 7)
and it is a prime, since it would otherwise be marked by a previous cycle. When you have
been through it all, all positions with an index that is not prime are checked.

You must now write a program where the user can enter a number (se the window below).
When you click the Test button, the application must insert a line in the list box that shows
whether the number is a prime number. To determine if this is the case, the program must
use the above algorithm and the class Bitmap from above. You can improve the algorithm
a bit by observing the following:

1. If a number has a prime factor (a prime number that divides the numbert), it or
another prime factor must be less than or equal to the square root of the number,
and the above iteration can therefore stop when starting index is greater than square
root of the number.
2. If you have reached the indexthat is not marked in a previous cycle, iskis a prime, and
you have to mark all the numbers that haskas divisor: 2k, 3k, 4k, , then it actually is
enough to start withk2, because the position else would be marked by a previous cycle.
3. It is not necessary in the bitmap to track other than the odd numbers, because all
the even numbers greater than 2 are not primes.

144
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO Operations
operatIonson
onsimple
sImpledata
datatypes
types

Eratosthenes
Eratosthenesalgorithm
algorithmisisactually
actuallyaavery
veryeffective
effectiveprime
primemethod,
method,but
butthe
theproblem
problemisisofof
course
coursethat
thatthe
thebitmap
bitmaptake
takeplace
placeininmemory
memoryevenevenififyou
youuse
usethe
theabove
aboveobservations.
observations.

EXERCISE
EXERCISE88
Create
Createaaproject
projectthat
thatyou
youcancancall
callEncoding.
Encoding.Add
Addthe
thefollowing
followingtwotwotest
testmethods,
methods,where
wherethe
the
first
firstwrite
writeaatext
texttotoaafile,
file,while
whilethe
theother
otherreads
readsthe
thetext
textagain:
again:

private static void test1()


{
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter("test1"));
writer.write("Sren Srensen\nPistolStrde 19\n6666 Borremose");
writer.close();
}
catch (Exception ex)
{
}
}

private static void test2()


{
try
{
BufferedReader reader = new BufferedReader(new FileReader("test1"));
for (String line = reader.readLine(); line != null; line = reader.readLine())
System.out.println(line);

145
145
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

reader.close();
reader.close();
}
}
catch
catch (Exception
(Exception ex)
ex)
{
{
}
}
}
}

Test
Test the
Test the two
the two methods
two methods from
methods from the
from the main()
the main() method.
main() method. Do
method. Do they
Do they have
they have the
have the expected
the expected result?
expected result?
result?

Write
Write two
Write two other
two other test
other test methods:
test methods:
methods:

private
private static
static void
void test3()
test3()
{
{
try
try
{
{
BufferedWriter
BufferedWriter writer
writer =
= new
new BufferedWriter(
BufferedWriter(
new
new OutputStreamWriter(new FileOutputStream("test2"),
OutputStreamWriter(new FileOutputStream("test2"), "UTF-8"));
"UTF-8"));
writer.write("Sren Srensen\nPistolStrde 19\n6666 Borremose");
writer.write("Sren Srensen\nPistolStrde 19\n6666 Borremose");
writer.close();
writer.close();
}
}
catch
catch (Exception
(Exception ex)
ex)
{
{
}
}
}
}

private
private static
static void
void test4()
test4()
{
{
try
try
{
{
BufferedReader
BufferedReader reader
reader =
= new
new BufferedReader(new
BufferedReader(new InputStreamReader(
InputStreamReader(
new
new FileInputStream("test2"),
FileInputStream("test2"), "UTF-8"));
"UTF-8"));
for
for (String line = reader.readLine(); line
(String line = reader.readLine(); line !=
!= null;
null; line
line =
= reader.readLine())
reader.readLine())
System.out.println(line);
System.out.println(line);
reader.close();
reader.close();
}
}
catch
catch (Exception
(Exception ex)
ex)
{
{
}
}
}
}

Note
Note that the difference isis that this time the file is opened in aa different manner (with an
Note that
that the
the difference
difference is that
that this
this time
time the
the file
file is
is opened
opened in
in a different
different manner
manner (with
(with an
an
additional
additional parameter),
parameter), and
and that
that the
the file
file has
has another
another name.
name. Test
Test also
also these
these two
two methods
methods from
from
additional parameter), and that the file has another name. Test also these two methods from
main()
main() and note that you get the expected result.
main() and
and note
note that
that you
you get
get the
the expected
expected result.
result.

146
146
146
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIOIO Operations
operatIonson
onsimple
sImpledata
datatypes
types

Write
Writetwotwomore
moretest
testmethods
methods(which
(whichyouyoucan
cancall
calltest5()
test5()and
andtest6()),
test6()),where
wherethe
thedifferences
differences
only
only isis that
that the
the file
file has
has a a different
different name
name (this
(this time
time test3)
test3) and
and a a second
second parameter
parameter
concerning
concerningencoding:
encoding:

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(


new FileOutputStream("test3"), "ISO-8859-1"));
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream("test3"), "ISO-8859-1"));

Test also these two methods. Write finally two test methods test7() and test8(), where the
Test also these two methods. Write finally two test methods test7() and test8(), where the
files are opened as follows:
files are opened as follows:

BufferedWriter writer = new BufferedWriter(


new OutputStreamWriter(new FileOutputStream("test4"), "UTF-16"));
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("test4"), "UTF-16"));

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

enroll by September 30th, 2014 and


save up to 16% on the tuition!
pay in 10 installments / 2 years
Interactive Online education
visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

147
147
JAVA 5: FILES AND JAVA IO operatIons on sImple data types
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Operations
operatIons on
on simple
sImple data
data types
types

and try also these two methods. If you uses Files to examines the four files, you can see
and try also these two methods. If you uses Files to examines the four files, you can see
how much they fills on the disk:
how much they fills on the disk:

- test1 48 bytes
-- test1
test1 48 bytes
- test2 48 bytes
-- test2
test2 48 bytes
- test3 45 bytes
-- test3
test3 45 bytes
- test4 92 bytes
-- test4
test4 92 bytes

Can you explains this 4 numbers?


Can you explains this 4 numbers?

EXERCISE 9
EXERCISE 9
Create a project that you can call FloatingPoint. The two wrapper classes Float and Double
Create a project that you can call FloatingPoint. The two wrapper classes Float and Double
have two constants MIN_VALUE and MAX_VALUE. Print these four constants on the screen
have two constants MIN_VALUE and MAX_VALUE. Print these four constants on the screen
and check how it fits with what has been said in the appendix (theyre actually not quite).
and check how it fits with what has been said in the appendix (theyre actually not quite).

You must then open the project for PaLib and add two methods to the class Binary:
You must then open the project for PaLib and add two methods to the class Binary:
/**
/**
* Converts the argument to a binary string of 32 bits.
* Converts the argument to a binary string of 32 bits.
* @param t The number to be converted
* @param t The number to be converted
* @return The argument converted to a binary string of 32 bits
* @return The argument converted to a binary string of 32 bits
*/
*/
public static String toBin(float t)
public static String toBin(float t)
{
{
}
}

/**
/**
* Converts the argument to a binary string of 64 bits.
* Converts the argument to a binary string of 64 bits.
* @param t The number to be converted
* @param t The number to be converted
* @return The argument converted to a binary string of 64 bits
* @return The argument converted to a binary string of 64 bits
*/
*/
public static String toBin(double t)
public static String toBin(double t)
{
{
}
}

In fact, it is trivial because the two wrapper classes has the methods Float.floatToRawIntBits()
In fact, it is trivial because the two wrapper classes has the methods Float.floatToRawIntBits()
and Double.doubleToRawLongBits() that you can use. Write equivalent methods, where you
and Double.doubleToRawLongBits() that you can use. Write equivalent methods, where you
can insert a separation character between the individual bytes:
can insert a separation character between the individual bytes:
public static String toBin(float t, char c)
public static String toBin(float t, char c)
{
{
}
}

148
148
148
JAVA 5: FILES AND JAVA IO Operations on simple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types
JAVA 5: FILES AND JAVA IO operatIons on sImple data types

public static
public static String
String toBin(double
toBin(double t,
t, char
char c)
c)
{
{
}
}

Use
Use these
these methods
methods to
to print
print the
the binary
binary representation
representation of of the
the numbers
numbers 123.45F,
123.45F, -123.45F,
-123.45F,
Use these methods to print the binary representation of the numbers 123.45F, -123.45F,
12345.6789 and
12345.6789 and -12,345.6789
and -12,345.6789
-12,345.6789 andand check
and check if
check if it
if it fits
it fits to
fits to what
to what is
what is said
is said in
said in the
in the appendix.
the appendix.
appendix.
12345.6789

The
The class
class Float
Float has
has three
three further
further constants:
constants: NEGATIVE_INFINITY,
NEGATIVE_INFINITY, POSITIVE_INFINITY
POSITIVE_INFINITY
The class Float has three further constants: NEGATIVE_INFINITY, POSITIVE_INFINITY
and NaN.
and NaN. Print
NaN. Print the
Print the binary
the binary representation
binary representation of
representation of these
of these constants.
these constants. Do
constants. Do the
Do the same
same for
the same for the
the class
class Double.
Double.
and for the class Double.

EXERCISE
EXERCISE 10
10
EXERCISE 10
In
In problem
problem 333 you
you you
you have
have written
written aaa class
class Bitmap,
Bitmap, which
which isis
is located
located in
in your
your class
class library
library
In problem you you have written class Bitmap, which located in your class library
PaLib. The
PaLib. The class
The class is
class is included
is included
included inin the
in the package
the package palib.util,
package palib.util, and
palib.util, and to
and to this
to this package
this package you
package you must
must add
you must add
PaLib. add
the
the following
following exception
exception class:
class:
the following exception class:

package palib.util;
package palib.util;
public class
public class UtilException
UtilException extends
extends Exception
Exception
{
{
public UtilException(String
public UtilException(String message)
message)
{
{
super(message);
super(message);
}
}
}
}

The class
The
The class Bitmap
class Bitmap has
Bitmap has four
has four instance
four instance methods
instance methods and
methods and four
and four static
four static methods
static methods that
methods that can
that can all
can all raise
all raise an
raise an
an
exception. You
exception.
exception. You must
You must change
must change the
change the class
the class so
class so all
so all these
all these methods
these methods instead
methods instead raises
instead raises an
raises an exception
an exception of
exception of
of
type UtilException.
type
type UtilException.
UtilException.

Open the
Open
Open the test
the test program
test program TestBitmap
program TestBitmap and
TestBitmap and see
and see ifif
see if itit
it still
still can
still can be
can be translated
be translated (which
translated (which itit
(which it should
should be).
should be).
be).
Expand the
Expand
Expand the program
the program with
program with another
with another test
another test method
test method which
method which provoke
which provoke an
provoke an exception
an exception (as
exception (as an
(as an example
an example an
example an
an
AND of
AND
AND of two
of two bitmaps
two bitmaps with
bitmaps with different
with different length)
different length) and
length) and test
and test whether
test whether you
whether you can
you can catch
can catch aaa UtilException.
catch UtilException.
UtilException.

149
149
149
JAVA 5: FILES AND JAVA IO Final example

5 FINAL EXAMPLE
As a final example I will show a program that can open any file and edit the content
whether you have the right to do so. The program should display the content of a file in
hexadecimal, and you can edit the file by modifying the individual bytes. The program can
edit all files without exception (text files, images, translated programs, etc.), but another
question is, whether you can get something out of it, and whether you can interpret the
hexadecimal codes.

Contrary to what has been the case with the final examples in the previous books, which
have primarily been focused on the process, I will in this example primarily look at the
result and hence the program code. I will start with a presentation of the program to explain
what the program is doing. When you opens the program, you get the following window:

150
JAVA 5: FILES AND JAVA IO Final example

The window contains two JTextArea components in a JSplitPane. The left component is the
one that displays the content of the file in hexadecimal and where you can edit the file.
The right component shows the content of the file interpreted as a text to the extent
that it is possible.

The function of the top seven buttons appears largely from the text where the first button
clear the window and thus creates an empty file, while the three next are used to respectively
open a file, save a file, and save a file as. Because files can be very large, the content of a
JTextArea can be so large that it is not manageable (the program will be slow), and therefore
large files are split into blocks, and the program works with a single block at a time. The
fifth and sixth button is used to scroll back and forth in these blocks. Finally opens the
last button, a dialog box where you can set the size of the blocks and how many bytes to
show per line:

151
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

After
After the
the program
program isis opened
opened there
there isis not
not yet
yet loaded
loaded any
any file,
file, but
but you
you may
may well
well start
start entering
entering
data.
data. Below
Below isis the
the window
window after
after II have
have entered
entered 66 bytes:
bytes:

Bytes
Bytes are
are entered
entered as
as their
their hexadecimal
hexadecimal codes.
codes. Now
Now you
you can
can not
not only
only enter,
enter, but
but you
you must
must
insert
insert aa byte
byte by
by pressing
pressing thethe Insert
Insert key,
key, which
which inserts
inserts aa byte
byte at
at the
the cursor
cursor position
position width
width
the
the value
value 00.
00. Then
Then you
you can
can change
change thethe value
value by
by typing
typing

0, 1, 2, , 9, a, b, , f

152
152
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example
JAVA 5: FILES AND JAVA IO FInal example

The
The program inserts a space between the individual bytes by itself, and it isis only for the
The program
program inserts
inserts aa space
space between
between the
the individual
individual bytesbytes by
by itself,
itself, and
and itit is only
only for
for the
the
sake
sake of
of readability.
readability. IfIf you
you save
save the
the above
above result
result in
in aa file
file and
and examine
examine the
the file,
file, you
you will
will find
find
sake of readability. If you save the above result in a file and examine the file, you will find
that
that the file contains the text
that the
the file
file contains
contains thethe text
text

ABCDEF
ABCDEF

IfIf you look at the program it isis in principle aa very simple program that alone contains aa
If you
you look
look at
at the
the program
program it it is inin principle
principle a very
very simple
simple program
program that
that alone
alone contains
contains a
main
main window and aa single simple dialog box. There isis also aa model, which, incidentally, is
main window and a single simple dialog box. There is also a model, which, incidentally, is
window and single simple dialog box. There also model, which, incidentally, is
not
not very
very complex,
complex, and
and the
the program
program consists
consists then
then of
of three
three classes.
classes. The
The most
most complex
complex isis the
the
not very complex, and the program consists then of three classes. The most complex is the
class
class MainView, which contains many details.
class MainView,
MainView, which
which contains
contains manymany details.
details.

5.1
5.1 THE MODEL
5.1 THE
THE MODEL
MODEL
Ill
Ill start with the model. The model must represent a data file, and in order to handle large
Ill start
start with
with the
the model.
model. The
The model
model must
must represent
represent aa data
data file,
file, and
and in
in order
order to
to handle
handle large
large
files,
files, that
that have
have been
been defined
defined aa simple
simple class
class that
that represents
represents aa data
data block
block to
to aa file:
file:
files, that have been defined a simple class that represents a data block to a file:

class Block
class Block
{
{
public byte[] buffer;
public byte[] buffer;
public int size;
public int size;

153
153
153
JAVA 5: FILES AND JAVA IO Final example
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO FInal
FInal example
example

public
public Block(int
Block(int size)
size)
{
{
buffer
buffer =
= new
new byte[2
byte[2 ** size];
size];
}
}
}
}

The
The class
class is
is consisting
consisting ofof aa byte
byte buffer
buffer and
and an
an int,
int, which
which defines
defines the
the number
number of of bytes
bytes inin the
the
buffer. The buffer is created by the constructor, where the parameter specifies
buffer. The buffer is created by the constructor, where the parameter specifies the buffers the buffers
size,
size, but
but you
you should
should note
note that
that the
the buffer
buffer is
is created
created asas twice
twice the
the size.
size. The
The reason
reason isis that
that it
it
should
should bebe possible
possible to
to add
add new
new bytes,
bytes, and
and therefore,
therefore, there
there must
must be
be some
some available
available space.
space. Note
Note
that
that instead
instead II could
could have
have applied
applied an an ArrayList<Byte>,
ArrayList<Byte>, butbut when
when II have
have defined
defined aa buffer
buffer as
as
an array, it is because you can directly read data to and directly write data
an array, it is because you can directly read data to and directly write data from an array from an array
when
when reading
reading andand writing
writing files.
files.

Also
Also note
note that
that II have
have deviated
deviated from
from the
the good
good principles
principles and
and defined
defined both
both variables
variables as
as public.
public.
It
It is to make the code simpler and make references to the classs variables simpler, and when
is to make the code simpler and make references to the classs variables simpler, and when
the class has package visibility and alone is a helper class for this program,
the class has package visibility and alone is a helper class for this program, I have allowedI have allowed
not
not toto use
use the
the usual
usual data
data encapsulation.
encapsulation. Its
Its actually
actually something
something that that you
you sometimes
sometimes see
see (and
(and
there
there might
might bebe good
good reasons
reasons for)
for) with
with simple
simple helper
helper classes
classes which
which areare only
only known
known within
within
the programs package.
the programs package.

The
The model
model class
class isis the
the following:
following:

public
public class
class Model
Model
{
{
private
private int
int lineLength
lineLength = = 32;
32; //
// number
number of
of bytes
bytes in
in aa line
line
private int blockSize = 524288;
private int blockSize = 524288; //
// size og af block in
size og af block in bytesbytes
private
private boolean
boolean changed
changed == false;
false; //
// if
if content
content of
of this
this block
block is
is changed
changed
private File file = null;
private File file = null; //
// reference
reference to the file to be edit
to the file to be edit

private
private List<Block>
List<Block> buffers
buffers =
= new
new ArrayList();
ArrayList();
private int current = 0;
private int current = 0;

By
By default
By default the
default the program
the program displays
program displays 32
displays 32 bytes
32 bytes
bytes in in
in aaa line,
line, and
line, and the
and the block
the block size
block size is
size is as
is as default
as default 524288
default 524288
524288
bytes
bytes (
bytes ( megabyte).
( megabyte).
megabyte). TheThe last
The last one
last one
one isis
is aaa bit
bit of
of aaa trade-off,
bit of trade-off, where
where aaa small
trade-off, where small block
small block
block sizesize means
size means
means
effectiveness
effectiveness in
effectiveness in the
in the editing
the editing of
editing of the
of the files
the files content,
files content,
content, but but in
but in return
in return many
return many blocks
many blocks
blocks to to be
to be edited
be edited one
edited one
one
at
at a time.
at aa time. Increasing
time. Increasing the
Increasing the block
the block size
block size also
size also increases
also increases
increases the the chances
the chances that
chances that the
that the whole
the whole file
whole file can
file can be
can be in
be in
in
aaa single
single block,
single block, but
block, but on
but on the
on the other
the other hand,
other hand,
hand, it it could
it could
could be be slow
be slow
slow toto edit
to edit the
edit the file.
the file. These
file. These
These areare the
are the two
the two
two
values that
values that
values can
that can be
can be changed
be changed
changed inin the
in the Options
the Options dialog
Options dialog
dialog box.box.
box.

154
154
154
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

The
The model
model also
also hashas aa variable
variable changed,
changed, which
which isis used
used toto keep
keep track
track of of the
the models
models on on state,
state,
and
and where
where itit isis changed
changed corresponding
corresponding toto that
that the
the file
file isis edited.
edited. Then
Then there
there isis the
the variable
variable
file
file that
that refers
refers to to the
the file
file been
been opened.
opened. IfIf the
the variable
variable isis null,
null, itit means
means that
that there
there isis not
not
loaded
loaded aa file.
file.

The
The list
list isis for
for blocks,
blocks, and
and byby small
small files
files (by
(by default
default less
less than
than aa
megabyte)
megabyte) there
there isis only
only
one
one block.
block. AlongAlong with
with the
the list
list isis that
that the
the variable
variable current,
current, which
which indicates
indicates the
the block
block that
that isis
currently
currently beenbeen displayed
displayed in
in the
the editor.
editor.

The
The model
model has
has several
several getget and
and set
set methods
methods and
and including
including methods
methods for
for navigating
navigating the
the variable
variable
current,
current, and
and there
there isis especially
especially more
more get
get methods
methods that
that return
return information
information about
about the
the models
models
state.
state. They
They are
are generally
generally simple,
simple, and
and II will
will not
not show
show these
these methods
methods here.
here.

The
The class
class also
also has
has methods
methods to
to read
read and
and save
save aa file.
file. Below
Below isis shown
shown the
the method,
method, which
which
opens
opens aa file:
file:

public boolean open(File file)


{
this.file = file;
buffers.clear();
try (RandomAccessFile f = new RandomAccessFile(file.getAbsolutePath(), "r"))
{
while (true)
{
Block block = new Block(blockSize);
block.size = f.read(block.buffer, 0, blockSize);
buffers.add(block);
if (block.size < blockSize) break;
}
changed = false;
return true;
}
catch (IOException ex)
{
clear();
return false;
}
}

The
The method
method isis inin principle
principle simple,
simple, and
and the the file
file isis read
read as
as aa RandomAccessFile.
RandomAccessFile. Input Input isis
performed
performed inin aa loop,
loop, which
which reads
reads aa block
block at at aa time,
time, and and the
the result
result isis that
that aa large
large file
file isis
divided
divided into
into several
several blocks.
blocks. Similarly
Similarly isis below
below aa method
method that that saved
saved the
the file:
file:

155
155
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example

public boolean save()


{
if (file == null) return false;
try (RandomAccessFile f = new RandomAccessFile(file.getAbsolutePath(), "rw"))
{
long length = 0;
for (Block block : buffers)
{
f.write(block.buffer, 0, block.size);
length += block.size;
}
f.setLength(length);
return true;
}
catch (Exception ex)
{
return false;
}
}

This method will overwrite the existing file, and you should especially note that the method
This method will overwrite the existing file, and you should especially note that the method
ends with updating the file length. It is necessary, as there may be deleted bytes, and the
ends with updating the file length. It is necessary, as there may be deleted bytes, and the
file thus has fewer bytes.
file thus has fewer bytes.

Join the best at Top masters programmes


3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
1st place: MSc International Business
School of Business and 1st place: MSc Financial Economics
2nd place: MSc Management of Learning

Economics! 2nd place: MSc Economics


2nd place: MSc Econometrics and Operations Research
2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier Beste Studies ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Masters Open Day: 22 February 2014

www.mastersopenday.nl

156
156
JAVA 5: FILES AND JAVA IO Final
FInal example

5.2
5.2 THE USER INTERFACE
This is essentially the class MainView, which is a relatively complex class. Since I do not
want to allow the user to edit the content arbitrarily, but only must enter the hexadecimal
values of the individual bytes, it is necessary to program the event handling for the keyboard
and also the mouse, and it is in fact why the class is a bit complicated. You are encouraged
to study the finished code thoroughly, but below I will briefly mention the most important.

The class defines the following variables:

private Model model = new Model();


private JTextArea txtEdit;
private JTextArea txtText;
private JLabel lblText = new JLabel();
private JLabel lblPosition = new JLabel();
private JScrollPane scroll1;
private JScrollPane scroll2;
private Scroller scroller;

Here are the two JTextArea components that are for the views of the current file, where
txtEdit is used to edit the content as hexadecimal values, while txtText is used to display
the content interpreted as text. The two JLabel components are placed in the bottom of the
window and are used to show respectively, the file name (and size), and where in the file
the cursor is. The two JScrollPane components are for encapsulation of the two JTextArea
components, and finally the last one whose type is Scroller. It is an inner class, which I will
not show here, but it must synchronize the two JScrollPane containers, such that if you
scrolls one then the other scrolls automatically. You are encouraged to study how it works.

As for the design of the user interface there is nothing new, but you should note the method

private JTextArea createEditor()


{
JTextArea txt = new HexEditor();
txt.setFont(new Font("FreeMono", Font.PLAIN, 18));
return txt;
}

which
which creates
creates the
the component
component txtEdit.
txtEdit. Its
Its type
type is
is HexEditor,
HexEditor, and
and it
it is
is an
an inner
inner class
class that
that
inherits JTextArea:
inherits JTextArea:

class HexEditor extends JTextArea


{

157
JAVA 5: FILES AND JAVA IO Final example
JAVA
JAVA
5: FILES
5: FILES
ANDAND
JAVA
JAVA
IO IO FInal
FInal
example
example

public
public
HexEditor()
HexEditor()
{ {
addKeyListener(new
addKeyListener(newKeyHandler());
KeyHandler());
setMouseListener();
setMouseListener();
setMouseMotionListener();
setMouseMotionListener();
} }

The The
Theclasss
classs
constructor
classs constructor
constructor addsadds
a new
adds aa new
newhandler
handler
handler forfor
for
events
events
events fromfrom
from thethe
the
keyboard,
keyboard,
keyboard, andand
andalso
also
alsocallcall
call
thethe
the
two two
twomethods,
methods,
methods, which
which
which remove
remove
remove event
event
event handlers
handlers
handlers forfor
for
thethe
the
mouse
mouse
mouse andand
anddefine
define
a new
define aa new
new
oneone
onethatthat
that doesdoes
does
nothing
nothing
nothing butbut
butto to
to
place
place
placethethe
the
cursor,
cursor,
if ifyou
cursor, if you
youclicks
clicks
clicksonon
on
thethe
the
component.
component.
component. TheThe
handler
The handler
handler must
must
must solve
solve
solve
thethe
the
problem
problem
problem thatthat
thatyouyou
you mustmust
mustnotnot
notplace
place
place thethe
the
cursor
cursor
cursor in in
in
front
front
frontof of
of
a space
aa space
space
oror
or
thethe
the
endend
endof of
of
a line.
aa line.
line.

AsAs
As
forfor
for
thethe
the
keyboard,
keyboard,
keyboard, thethe
the
program
program
beyond
program beyond
thethe
beyond the
1616
16
keys
keys
to to
keys to
hexadecimal
hexadecimal
digits,
hexadecimal digits,
thethe
digits, the
program
program
program
supports
supports
supports thethe
the
following
following
followingkeys:
keys:
keys:

- --insert
insert
- insert
- --delete
delete
- delete
- --thethe
- the44arrow
4 arrow
arrowkeyskeys
keys
- --home
home
- home andand
ctrlctrl
and ctrl
home
home
home
- --endend
- endandand
ctrlctrl
and ctrl
end end
end
- --pagedown
pagedown
- pagedown
- --pageup
pageup
- pageup

wherein
wherein
whereinthethe
the
two two
twofirst
first
modifies
first modifies
thethe
modifies the
content,
content,
while
content, while
thethe
while the
other
other
navigates
other navigates
thethe
navigates the
cursor.
cursor.
cursor.

The
The
event
The event
handler
event handler
forfor
handler for
thethe
the
keyboard
keyboard
is is
keyboard called
is called
called

public
public
void
void
keyPressed(KeyEvent
keyPressed(KeyEvent
e) e)
{ {

and
and
and mainly
mainly
mainly consists
consists of of
consists of aa switch,
a switch,
switch, where
where
whereis isswitched
is switchedonon
switched thethe
on the keyboard
keyboard
keyboard codes
codes to to
codes bebe
to be treated.
treated.
treated.
Whether
Whether
Whether it is a key
it isit ais key
a key to
to to be
be be treated
treated
treated or
or or not
notnot the
thethe following
following
following statement
statement
statement is executed
is executed
is executed

e.consume();
e.consume();

158
158 158
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

which
which means
means that
that the
the event
event isis not
not passed
passed onon and
and thus
thus not
not to
to the
the usual
usual event
event handling
handling in
in the
the
base
base class
class JTextArea.
JTextArea. Most
Most entries
entries in in the
the switch
switch statement
statement calls
calls aa method
method that
that performs
performs thethe
desired action. As an example is shown below the method called, if the insert
desired action. As an example is shown below the method called, if the insert key is entered:key is entered:

private void insertChar(int p)


{
if (model.getBlock().buffer.length == model.getBlock().size + 1) return;
int n = p / 3;
if (p % 3 > 0) ++n;
for (int i = model.getBlock().size; i > n; --i)
model.getBlock().buffer[i] = model.getBlock().buffer[i 1];
model.getBlock().buffer[n] = 0;
++model.getBlock().size;
showFile();
model.change();
showPosition();
setCaretPosition(p);
}

> Apply now

redefine your future


AxA globAl grAduAte
progrAm 2015
- Photononstop

axa_ad_grad_prog_170x115.indd 1 19/12/13 16:36

159
159
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

The
The parameter
parameter isis thethe cursor
cursor position.
position. The The first
first thing
thing that
that happens
happens isis that
that the
the cursor
cursor position
position
must
must be be converted
converted to to the
the byte
byte position
position in in the
the model,
model, where
where toto insert
insert aa new
new byte,
byte, and
and here
here
one
one must
must note
note that
that aa byte
byte because
because of of the
the space
space fills
fills three
three characters
characters in in the
the component.
component.
Here
Here areare adopted,
adopted, ifif the
the cursor
cursor isis in
in front
front ofof aa byte,
byte, aa new
new byte
byte must
must be be inserted
inserted inin front,
front,
and
and ifif the
the cursor
cursor isis inside
inside the
the byte,
byte, aa newnew byte
byte must
must be be inserted
inserted after.
after. Within
Within thethe byte
byte
can
can be
be inserted,
inserted, thethe subsequent
subsequent bytesbytes areare moved
moved one one place
place forward
forward and and thethe new
new byte
byte will
will
have
have the
the value
value 0. 0. Also
Also note
note that
that the
the size
size of
of the
the buffer
buffer isis counted
counted up up by by 1.1. Next
Next isis called
called aa
method
method showFile()
showFile() (a (a method
method alsoalso used
used inin other
other contexts)
contexts) which
which isis the
the method
method thatthat shows
shows
the
the content
content of of the
the file
file (actual
(actual the
the current
current block).
block). Finally
Finally thethe method
method showPosition()
showPosition() isis called,
called,
which
which updates
updates thethe status
status bar.
bar. These
These methods
methods are, are, in
in principle,
principle, simple
simple and and notnot shown
shown here.
here.
II will
will instead
instead show
show the the method
method thatthat isis called
called when
when aa bytebyte has
has to
to be
be changed:
changed:

private void changeChar(char ch)


{
int p = getCaretPosition();
String text = getText();
setText(text.substring(0, p) + ch + text.substring(p + 1));
byte b2 = (byte)(ch >= '0' && ch <= '9' ? ch '0' : ch 'a');
int n = p / 3;
model.getBlock().buffer[n] = p % 3 == 0 ?
(byte)(((b2 << 4) | (model.getBlock().buffer[n] & 0x0f)) & 0x000000ff) :
(byte)(((model.getBlock().buffer[n] & 0xf0) | b2) & 0x000000ff);
model.change();
setCaretPosition(p);
}

The
The methods
methods parameter
parameter isis the
the character
character entered,
entered, andand the
the first
first thing
thing that
that happens
happens isis that
that
the
the component
component isis updated
updated with
with the
the character
character inin the
the right
right place.
place. Then
Then also
also the
the model
model must
must
be updated. First is determined the characters value as a value between
be updated. First is determined the characters value as a value between 0 and 15 inclusive. 0 and 15 inclusive.
Next,
Next, the
the cursor
cursor position
position again
again must
must bebe converted
converted into
into the
the right
right byte
byte position
position in in the
the model,
model,
and then it is determined whether it is the first or the last of the two digits
and then it is determined whether it is the first or the last of the two digits to be changed. to be changed.
You
You should
should note note that
that this
this method
method does
does notnot call
call the
the showFile(),
showFile(), whatwhat itit really
really should.
should. The
The
reason is performence and the result is that the right component that
reason is performence and the result is that the right component that displays the content displays the content
as
as text
text isis not
not updated,
updated, andand therefore
therefore dodo not
not necessarily
necessarily show
show thethe right
right content.
content.

5.3
5.3 THE
THE DIALOG
DIALOG BOX
BOX
This
This leaves
leaves the
the dialog
dialog box,
box, which
which isis used
used to to change
change the
the parameters
parameters of of thethe block
block size
size and
and
the
the number
number of of bytes
bytes per
per line.
line. There
There isis not
not much
much to to explain,
explain, but
but youyou should
should note,
note, that
that
ifif the
the dialog box is used, the result is a blank file, and there is not loaded any file. Its aa
dialog box is used, the result is a blank file, and there is not loaded any file. Its
somewhat
somewhat easy easy solution,
solution, but
but the
the reason
reason isis to
to change
change the
the block
block size,
size, itit isis necessary
necessary toto create
create
new blocks. You should also note that the coupling between the MainView
new blocks. You should also note that the coupling between the MainView and the dialog and the dialog
box
box isis strong
strong but
but simple
simple and
and isis also
also aa matter
matter of of reaching
reaching easy
easy to
to the
the target.
target.

160
160
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

APPENDIX A
If
If youyou technically
technically have
have to
to deal
deal with
with computers,
computers, you you can
can not
not ignore
ignore the
the binary
binary number,
number, as
as
there
there are are aa lot
lot of
of details
details that
that you
you can
can not
not explain
explain without
without having
having knowledge
knowledge of of the
the numbers
numbers
and
and their their binary
binary representation.
representation. The
The following
following isis aa brief
brief introduction
introduction toto the
the binary
binary numbers
numbers
and
and including
including thethe hexadecimal
hexadecimal system
system in
in view
view ofof applications
applications inin computer
computer technology,
technology, but
but
itit isis by
by no
no means
means anan accurate
accurate treatment
treatment of
of number
number systems
systems in
in general.
general.

The
The numbers
numbers presented
presented to
to us
us at
at the
the school
school are
are decimal
decimal numbers
numbers in
in which
which numbers
numbers are
are
represented
represented by
by 10
10 symbols,
symbols, for
for example
example

18207

When we
When we meet
meet the
the number,
number, we we know
know exactly
exactly what
what itit means,
means, because
because wewe know
know thethe 10
10
symbols and
symbols and their
their interpretation
interpretation in in relation
relation to
to where
where aa symbol
symbol appears
appears in
in the
the number.
number. The
The
decimal number
decimal number system
system isis aa positional
positional number
number system
system as
as the
the value
value of
of aa digit
digit isis determined
determined
by its
by its position:
position:

18207 == 11 tens
18207 tens of
of thousands
thousands plus
plus 88 thousands
thousands plus
plus 22 hundreds
hundreds plus
plus 00 tens
tens plus
plus 77 ones
ones

When we
When we are
are taught
taught to
to work
work with
with these
these numbers,
numbers, we
we find
find them
them simple
simple and
and easy
easy to
to understand,
understand,
but the
but the reason
reason is,
is, that
that people
people very
very easy
easy and
and very
very safe
safe can
can survey
survey and
and learn
learn the
the 10
10 symbols.
symbols.

The decimal
The decimal system
system or or 10-number
10-number system
system isis not
not the
the only
only number
number system
system that that people
people have
have
historically used.
historically used. For
For example,
example, waswas previously
previously used
used aa 60-number
60-number system,
system, which
which you
you can
can
see the
see the remains
remains ofof in
in our
our division
division of of the
the time:
time: 11 hour
hour divided
divided into
into 60
60 minutes,
minutes, 11 minute
minute
divided into
divided into 60
60 seconds.
seconds. The
The 60-number
60-number system
system has
has also
also beenbeen used
used inin commercially
commercially tradetrade
calculation. The
calculation. The system
system hashas several
several advantages.
advantages. 6060 has
has many
many divisors,
divisors, which
which means
means that
that you
you
can formulate
can formulate many
many rules
rules of
of arithmetic,
arithmetic, andand even
even quite
quite largelarge numbers
numbers does does notnot take
take up
up so
so
much, but
much, but there
there isis however
however also
also aa very
very big
big disadvantage,
disadvantage, namelynamely that
that thethe system
system requires
requires
60 symbols
60 symbols (there
(there are
are actually
actually historical
historical writings
writings that
that showsshows the
the 60
60 symbols).
symbols). That
That the
the
10-number system
10-number system that
that has
has become
become the the preferred,
preferred, itit isis believed
believed that
that itit isis because
because we
we have
have
10 fingers.
10 fingers. Actually,
Actually, there
there are
are also
also examples
examples of of how
how people
people havehave used
used aa 20-number
20-number system
system
(we also
(we also have
have 10
10 toes).
toes).

161
161
system has also been does
numbers used not
in commercially
takeupupsosomuch,tradebut
much, calculation. The system
thereisishowever
however has
alsoa avery
veryseveral advantages. namely
bigdisadvantage,
disadvantage, 60 thatthe
the
numbers does not take but there also big namely that
has many divisors, which
systemrequires means that
requires6060symbols you
symbols(therecan formulate
(thereare
areactuallymany rules
actuallyhistorical of arithmetic,
historicalwritings
writingsthat and
thatshows even
showsthe quite large
the6060symbols).
symbols).That Thatthethe
system
numbers does10-number
not take up so much,
system but
thathas there
hasbecome is however
become also a itvery
thepreferred,
preferred, big disadvantage, namely that the 10 fingers.
10-number system that the it isisbelieved
believed thatit itisisbecause
that because we wehavehave 10 fingers.
system requires 60 symbols
Actually, there (there
arealsoareexamples
also actually historical writingshavethat used
showsa the 60 symbols). That thealso have 10
JAVA 5: FILES Actually,
AND JAVA there
IO are examples ofofhow howpeople
people have used 20-number
a 20-number system
system (we
(we
Final also have 10
example
10-number system
toes). that has become the preferred, it is believed that it is because we have 10 fingers.
toes).
Actually, there are also examples of how people have used a 20-number system (we also have 10
toes). 10 where
If you look atIfIfintegers
you lookatin
youlook the
atintegers 10-number
integers ininthe system,
the10-number
10-number theythey
system,
system, cancan
they bebebe
can written
writtenas
written as ==
as 10
=0
=0 where
where thethe
the Ifnumber number
has
number +has1+
n has +11digits,
digits,
digits, and andand0,0, 1,
1, . ....,., all
allisisis
all oneone
ofofthe
one
they can be written as =
the symbols
ofsymbols 0,0,1,1,2,2,...,...,
the symbols 0,9.9.1,
As
Asan
anexample
2, example
, 9.isis
As
you look at integers in the 10-number system, =0 10 where the
an example
number hasis + 1 digits, and 0, 1, . . . , all is one
0 of the symbols
1 0, 1, 2, ..., 9. As3 an example 4 is
18207==77 10
18207 10
0 + 0 10
+ 0 101 ++22 10
10++88 10
10
3 + 1 10
+ 1 104
0 1 3 4
18207 =
==44and 7 10 + 0 10 + 2 10 + 8 and 10 +=1 1
10
Thatisis
That and0 0==7,7, 11==0,0, 22==2,2, 33==88and 4 4= 1. .

That is = 4 =therefore
and say
Wee 7, 1 = that
0, 2the= decimal
2, 3 = 8system
and = 1positional
.
Wee say 0 therefore that the decimal system is4isa apositional numbersystem
number systemwithwithbase
base10.10.This
This
presentationofofthe
presentation thenumbers
numberscan canimmediately
immediatelybebegeneralized
generalizedtotoother
otherbases,
bases,andandactually
actuallythere
thereisisa a
WeeWee say say
therefore
therefore
number
that
that the
the decimal
system decimal
for any
system
system
natural is isa apositional
number
positional
greater number
than
number
1. system
As an
system with
with base
example the
base
This 10. This
10.60-number system
number system for any natural number greater than 1. As an example the 60-number system
presentationof
presentation ofthe
the numbers
numbers
mentioned above can
iscan
a immediately
immediately
system where be
thegeneralized
be
base to isother
generalized
number 60. bases,
to andbases,
other actuallyandthere is a
actually there
mentioned above is a system where the base number is 60.
is a number
number system for any natural number greater than 1. As an example the 60-number system
system for any natural number greater than 1. As an example the 60-number
mentioned above is a system where the base number is 60.
system mentioned above is a system where the base number is 60.
The binary number system 110
110
THE BINARY NUMBER SYSTEM 110
TheThe
binary number
binary numbersystem is simply
system a positional
is simply number
a positional system
number withwith
system basebase
2. Thus, it isit only
2. Thus, is only
necessary with two symbols, and here are used 0 and 1. A number could, for instance be
necessary with two symbols, and here are used 0 and 1. A number could, for instance be

= 2
=0

where 0, 1, . . . , all are 0 or 1. If = 7 and

0 = 1
1 = 0
2 = 0
3 = 0
4 = 1
5 = 1
6 = 0
7 = 1

is

= 1 27 + 0 26 + 1 25 + 1 24 + 0 23 + 0 22 + 0 21 + 1 20

This number is also written as = 101100012 where the last number 2 tells that it is a number from
the 2-number system. As you can see, the 2-number system is in principle completly equivalent to the
10-number system, where a number is presented as a sequence of symbols - 10 symbols in 10-number
system and 2 symbols in the 2-number system - and the numbers value is determined by the symbols
position. The difference is that a symbol is interpreted as a power af 2 instead of a power of 10, and as
such is the binary system simpler, since a given power of 2 either is included in the number (the
symbol is 1) or it is not (the symbol is 0).

If you look at the above construction, it is easy to determine the value of a number in the 2-number
system by a simple calculation of powers of 2:

162
= 1 27 + 0 26 + 1 25 + 1 24 + 0 23 + 0 22 + 0 21 + 1 20
The binary number system is simply a positional number system with base 2. Thus, it is only
The
The binary
binary
necessary
Thenumber
withnumber
binary
system
system
two symbols,
number
is simply
is
and here simply aand
are used 0a
system
positional
positional number
number
1. A number system
could, forsystem with
instance with
be base 2.
base 2. Thus,
Thus, it
it is
is only
only
necessary with two symbols, and here are used
necessary with two symbols, and here are used 0 and 1. A0 and 1. A number could, for instance be
number could, for instance be
The binary number system is simply a=positional
2number system with base 2. Thus, it is only
necessary
JAVA 5: FILES AND JAVAwith IO
two symbols, and here are used 0 and 1. A number could, for instance be Final example
= 2=0
=0
=
= 2
2
where 0, 1, . . . , all are 0 or 1. If = 7 and ==0 2
where allareare
where 0, 1, . . . , all 0 or01. or
If 1.
= If n = 7 and=0
7 and
=0

0,
where 1, . . . , allall are are 0 0 or
or 1.
1. If =
If =07 10 = 1
7=and
and
where 0, where
1, . . . ,
0, 1, . . . , all are 0 or 1. If = 7 and
1 = 01 = 0
2 = 0

2 0=
=0=1
= 11
3 = 0 0 0

4 = 1
31 =
1 =0
10
= =00
=00
5 = 1

42 ==
2 =0
21
3 = 0
6 = 0
== 10
0
53 3=4 =1
7 = 1 == 01

64 4=5 =11

is


75 5=
=
=61=1
10
66=
=7 =0
01
is = 1 2 + 0 2 + 1 2 + 1 2 + 0 2=+10 22 + 0 21 + 1 20
7 6 5 4 3
is 77 = 1
This number is also written
7 as =6101100015 where the4last number3 2 tells that2it is a number
1 from 0
is = 1 2 =
isthe 2-number +10272+ + 126 +2 12+
0 the 21
5 2 +
24in0
+ 1 is 0 223++00 222 ++00 212+ 1+ 120 2
+principle
system. As you can see, 2-number system completly equivalent to the
10-number system, where a number is presented as a sequence of symbols - 10 symbols in 10-number
This number is also written 66=as where the last 2number 21isit+
atells that0fromit is a
+10110001
This number 2is also = 210110001
1 written as where the last 3 number
222 completly
tells
0thethat +is1 1anumber
2to0 the from
This
and = number
1 2 7isthe
+ also written as 5 4where the last number 2tells that symbols
it number
system thesymbols
= 2-number
+0
2in7 system. 2
02-number
2
As
+
you
1
1can see,
system 2-5and+
+
the
12
the
1 2
22 4 +
numbers
2-number
0
0value
+system 2 +
2is3isin
+ 0
0 2
determined
principle
+
+ by 0 2
21equivalent 2
number
theposition.
2-numberfrom the 2-number
The difference
system. is that
As cansystem.
youa symbol the As
is interpreted
see, you
2-number can
as a power see,
systemaf 2 is the
instead 2-number ofsystem
of a powercompletly
in principle 10, and as is in principle
equivalent to the
such is the10-number
binary system system, wheresince
simpler, a numbera given is presented
power ofas2 aeither
sequence of symbols
is included in the - 10number
symbols(the in 10-number
10-number
completly system,
equivalent where a
to the number is presented as a sequence of symbols - 10 symbols in 10-number
This
This number
number
symbol oris
is 1)systemisit also
notwritten
also
isand written
2(the
symbols
symbol asin10-number
as isthe
=
= 10110001
10110001
0).2-number
system,
system where
2 where
2 - andwhere
the
the
the a number
last
last
numbers number
value is 2
number 2is presented
tells
tells
determined that
thatbyit isasaasymbols
is
it the anumber
sequence
number from
from
system
ofthe and
symbols 2 symbols
10 symbols in the in 2-number
10-number system system - and the
and numbers
2 symbols value
in is
the determined
2-number by the
system symbols
and
the 2-number system. As you can see, the 2-number system is in principle completly equivalent to the
2-number system.
position. The As you
difference can
is see,
that a the
symbol 2-number
is interpretedsystem
as a is
power in principle
af 2 instead completly
of a power of equivalent
10, and as to the
position.
10-number
the Thesuch
If numbers
you look atdifference
theis above
system,
value thewhere
is is
binary that
a
construction,
determined a symbol
system
number simpler,
it isisby isthe
interpreted
since
presented
easy to a given
determine
symbolsas a as avalue
power power
sequence
the of of
position. a af
2 either
of 2 isinstead
symbols
number
The included
in the-
difference of
10 inasymbols
2-numberpower
the number
is that of
in 10,
a(theand as
10-number
symbol
10-number system, where a number is presented as a sequence of symbols - 10 symbols in 10-number
such is the symbol is 1) or it issimpler,
notpowers
(the symbol isa0).given power of 2 either is included in the number (the
system
system
issystem andabinary
by
and
interpreted
simple
2 symbols
2 symbolssystem
calculation
as a power in the
in theof 2-number
af2-number
2 instead
since
of 2: system
of a --power
system and the
and theofnumbers
numbers
10, andvalue value
as such is determined
is determined
is the binary by the
by the system
symbols
symbols
symbol is 1)
position. The or difference
it is not (the is symbol
that a is 0). is interpreted as a power af 2 instead of a power of 10, and as
symbol
position.since
simpler, The
If=you difference
1alook
given
27 +at0the is2above
power6that aconstruction,
+ 1 of symbol
252+either1 is2it4interpreted
+is 0easy
is included
2to + as
0 ain
3 determine
2power
2 the
+the af
21 2+instead
number
0 value 0 of a
2(the
of1 a number inpower
symbol of
the 2-numberis 10,
1) and
or itas
such is the binary
system by asystem
simple simpler,
calculation since
of powers a given
of 2: power of 2 either is included in the number (the
issuch
If not is
you
the symbol
(the
look at
binary system
the above is 0).= 128 simpler,
+ 32 +since
construction,
16 + 1a =given
it is easy
177 power of 2 either is included in the number (the
to determine the value of a number in the 2-number
symbol
symbol is is 1)
1) or or itit is
is not
not (the(the 7symbol
symbol 6is is 0).
0). 5
system by a simple calculation of
To compare the two systems, please note the+following:
= 1 2 + 0 powers
2 1of 2:
2 + 1 24 + 0 23 + 0 22 + 0 21 + 1 20
IfIfyou
you look
look at theabove
at the
the aboveconstruction,
construction,
= 128 + isiteasy
it 32 +is16
easyeasy to determine
+ 1determine
to = 177 the of
the value
value valuenumber
of a number in the
If you look at above construction, it is to determine the of aa number in the
in the 2-number
2-number
7 =
2-number system
10 a
02 = 0by
system =simple2by
1 100
system by aTosimple 2+a04 26 of
simple
calculation
10 1 225=+
calculation
+1000
powers of
4
81012:of21100
powers 2of310+
+ 20= 12 2: 0 22 + 0 21 + 1 20
comparecalculation of powers
the two systems, of 2:
please note the following:
12 = 110 1012 = 4=10 128 1001
+ 322 =+ 916
10 + 1 1101 2 = 1310
= 177
102 = 210 11027 = 610 6 10102 =51010 1110 4 2 = 1410
112 = 310

02=
==11
010
2
2 7 + 0100
+ 0
1112 = 710

2
2 +
26=+ 1
410 2 +
5 10001 2
=
10112 = 1110 11112 0
1 2 + 1
2 2 +
4810
+ 0 233 +
1100 0 12
2 =
= 15210 + 0 2
2 2
102 +0
+ 211 +
0 2 +1 200
1 2
To compare 1the
2 =two
110 systems, =please
101 note
10 32the
2 = 4+
128 following:
+1001 +=1
16 2+ 19==
10 1771101 = 1310
= 128 + 32 + 16 177 2
102 = 210 1102 = 610 10102 = 1010 11102 = 1410
0 =0 112 = 3100 = 111
4 2 = 71010001111011
= 28= 1110 110011112 = = 15
1210
To
To
To compare
2 compare
compare
10 the
thetwo
the twosystems,
two
10
systems, please
2systems, note
please
please
10 the
2 following:
notenote
the the10following: 2
following: 10
12 = 110 1012 = 410 10012 = 910 11012 = 1310
10
0
022 =
=0210
010
110
100
100 22 ==64
2 =41010
10
1010
1000
1000 22 ==10
2 = 810
111 1110
810 1100
1100 22 ==14
12
2 = 12
1010
10
11
1 = 3
110
122 = 110
111
101
101 2 2
2
==
=74
4
1010
10
1011
1001
1001 2 2
2
==
= 119
910
10
1111
1101
1101 2 2
2
==
=15
13
13
1010
10
10 = 2
102 = 210
2 10 110 =
1102 = 610
2 6 10 1010 = 10 1110
10102 = 1010 11102 = 1410
2 10 2 = 14 10
11 = 3
1122 = 310
10 111 = 7
11122 = 710 10 1011 =
101122 = 111011 10 1111 = 15
111122 = 1510 10
111

You can thereof immediately see that the numbers in the binary system takes up more space
111
111
than numbers in the decimal system.

163
You
JAVAcan5: thereof
FILES AND immediately
JAVA IO see that the numbers in the binary system takes up more space
Final than
example
You
You can
numbers thereof
in the
can immediately
decimal
thereof system. see
immediately see that
that the
the numbers
numbers inin the
the binary
binary system
system takes
takes up
up more
more space
space than
than
You
numberscan in thereof
the immediately
decimal system. see that the numbers in the binary system takes up more space than
numbers
You can
Below in
are the
some decimal
thereof system.
immediately
examples of see that the
positive numbers
integers in theinbinary
written system takes
the 2-number up more
system, andspace
howthan
to
numbers
Below are in the
some decimal
examples system.
of positive integers written in the 2-number system, and how to convert
numbers
convert in the decimal
those numbers system.
toofthe 10-number system:
Below
those
Below are
are some
numbers to theexamples
some 10-number
examples positive
positive integers
of system: integers written
written in
in the
the 2-number
2-number system,
system, and
and how
how to to convert
convert
Below
those are
numbers someto examples
the of
10-number positive
system: integers written in the 2-number system, and how to convert
those
Below numbers
are some to the 10-number
examples system: integers written in the 2-number system, and how to convert
of positive
those numbers to the 10-number system:
1110000111110
those numbers = 212
to the 10-number + 211 + 210 + 25 + 24 + 23 + 22 + 21
system:
12 11 10 5
5 + 24 4 + 23 2 1
1110000111110
1110000111110 = 4096 =
=2+12
2 +
+2
2048 211++ + 2
210
1024 +
+2 32
2 ++ 216 + +
+42
+2833 + 222+++2 22=11 7230
12 11 10 5 4
1110000111110 = = 2 12 + 2 11+ 2 10+ 2 + 2+ 416
+ 2+38 + 2 42++22 1= 7230
1110000111110 = 4096= 2+
4096 + 2048
+2 +
2048 ++1024
2 ++
1024 +2532
32++2 16 ++2 8+++24 + 2 = 7230
9= 4096 8 +7 20486 + 1024 5 +4 32 + 3 16 + 2 8 +1 4 + 0 2 = 7230
1111111111 = 2 + = 24096
+ 2+ + 2 ++21024
2048 + 2 ++322 ++16 2 ++82+ + 4+ 2 2==1023 7230
9
9 + 28 8 + 27 7 + 26 6 + 25 5 + 24 4 + 23 3 + 22 2 + 21 1 + 20
1111111111 = 2
1111111111 = 29 + 28 + 27 + 26 + 25 + 24 + 23 + 22 + 21 + 20 = 1023 0 = 1023
1111111111 = 2 9+ 2 8+ 2 7+ 2 6+ 2 5+ 2 4+ 2 3+ 2 2+ 2 1+ 2 0= 1023
1111111111 1110000001
= 2 + 2 +=2512 + 2+ 256 + 2 ++128 2 + + 21 = + 897
2 + 2 + 2 = 1023
1110000001
1110000001 = 512 + 256 + 128 + 1 =
= 512 + 256 + 128 + 1 = 897
897
1110000001 = 512 + 256 10 + 128 + 1 = 897
10000000000
1110000001 = 512=+225610 =+1024128 + 1 = 897
10000000000 =
10000000000 = 210 = 1024 2 10 = 1024

ToTo
determine the value of a binary 10000000000
number - or in other = 2 10=to1024
determine the value of a binary number
10000000000 or=words
in2 other convert
words to
= 1024 it to the decimal
convert it to system - is
the decimal
To
simpledetermine
and is
To determine the
just a value
question
the value of ato binary number
remember
of ais binary the - or
powers in other
of 2. words
The to
otherconvert
way toit to the
convert decimal
a number system
in the--tois
system
To
is simple
determine the value
andof a
just anumber
binary
question
number
- ortoin remember
- or in
other wordsthe
other words
to convert
to
powersit
convert it
to the
of
to the
decimal
2. The
decimal
system
other way
system -
is
is
simple
10-number
simple and is
system
and just
to
is just a
a question
binary to
numberremember
requiresthe
a powers
little of
more. 2. The other way to convert a number in the
To determine
convert a the avalue
number question
in the to remember
of a10-number
binary number the- or
system powers ofbinary
intoother
a 2. Thenumber
words other
to wayrequires
convert totoconvert
it a number
the adecimal
little in the
system
more. - is
simple and is just a question to remember the powers of 2. The other way to convert a number in the
10-number system to aa binary
10-number
simple andsystem
is just to binary number
a question number requires
requires
to remember
a little
little more.
theapowers more.
of 2. The other way to convert a number in the
10-number
Given a system
number, for to a
examplebinary number
2423, one requires
can a little
determine more.
the largest power of 2 that is less than or equal
10-number system to a binary number requires a little more.
Given
Given aanumber,
number, 11for
for example
example 2423,2423, onedetermine
can determine the largest poweris of 2 thatorisequal
less
to Given
the number. It is 2for example
a number, = 20482423,and one can determine the largest
one can the largest power
power of
of 22 that
that is less
less than
than or equal
Given
than a number,
or forthe
equalIttois 2 example
11 number.
= 2423,
It one
is 2can
11 determine the largest power of 2 that is less than or equal
= 2048 and
to the
the number.
toGiven number.
a number, 211
It isfor11
= 2048
2048
example and
and one can determine the largest power of 2 that is less than or equal
2423,
to the number. It is 2 11= 2048 and 11
to the number. It is 2 = 2048 and 2423 = 2 + 375
11
2423
2423 = =2 211 +
+ 375
375
2423 = 21111+ 375
The largest power of 2 which is less than or equal 2423to=375 2 is+2375 = 256. That is
The largest power
largestpower
The largest of 2
powerof of which is
2 which
2 which less
is less than
is than or
less or equal
than to 375
or toequal
equal is 2 =
= 256
375 isto2375 is 2..8That
256 is
= 256.
That is That is
The largest power of 2 which is less than 11 or equal to 37511 is 2 8 = 256. That is
The largest power of 2 which 2423 = 2than+or375
is less equal=to2375+is22+=119 256. That is
11
11 + 375 = 211 8
2423 = 2
2423 = 211 + 375 = 211 +
+ 2
2 8 + 119
+ 119
2423 = 2 11+ 375 = 21111+ 288+ 119
The largest power of 2 which is less than=or2equal
2423 + to
375119=is22 + = 264+and 119
The largest
largest power of 2 which is less than or equal to 119 is 2and
The largest power
power of
of 2
2 which
which is
is less
less than
than or
or equal
equal to
to 119
119 is
is 2
2 =
= 64
64 and
6
= 64 and
The largest power of 2 which 11 is less than 11 or equal8 to 119 is 211 = 64 8and 6
2423 = 2
The largest power of 2 which + 375 = 2 + 2 + 119 =
is less than or equal 8to 119 is 2 =2 + 64 and2 +6 55
2 +
11
11 + 375 = 211 11 + 28 + 119 = 211 11 + 28
2423
2423 = 211 + 375 = 211 + 28 + 119 = 211 + 288 +
= 2 +2 26 +
+ 55
55
2423 = 2 11+ 375 = 2 11+ 2 8+ 119 = 2 11+ 2 8+ 266+ 55
The largest power of 2423
2 which =is2less+than375or=equal
2 + to 55
2 is +2119 == 322and+ 2 + 2 + 55
The largest
The largest power
power of 2
of of which
2 which is less
is less than
than or
or equal
equal to 55
toequalis 2 =
= 32
2 55
55 is to 32 and
and
The largest power 2 which is less than or is 2 5
= 32 and
The largest11power of 2 which
11 is less
8 than or equal
11 to 55 8 is 26 = 32 and 11
2423 = 2 + 375 = 2 + 2 + 119 = 2 + 2 + 2
The largest power of 2 which is less than or equal to 55 is 2 = 32 and + 55 = 2 + 28 + 26 + 25 + 23
11 11
11 + 28 8 + 119 = 211 11 + 28 8 + 26 6 + 55 = 211 11 + 28
8 + 26
6 + 25
2423
2423 = =2 211 +
+ 375
375 =
= 2
2 + 2 + 119 = 2 + 2 + 2 + 55 = 2 + 2 + 2 + 255 +
+ 23
23
11 11 8 11 8 6 11 8 6
2423
To resume, =
and2 +
you 375 = 2
11 will find: 11
+ 2 8
+ 119 = 2 11
+ 2 8
+ 2 6
+ 55 = 2 11
+ 2 8
+ 2 6
+ 2 5
+ 23
2423 = 2 + 375 = 2 + 2 + 119 = 2 + 2 + 2 + 55 = 2 + 2 + 2 + 2 + 23
To
To resume,
resume, and
and you
you will
will find:
find:
To
To resume,
resume, and you
and will
you find:
11 will
2423
To resume, and = 2 will
you 28find:
+find: + 26 + 25 + 24 + 22 + 21 + 20 = 1001011101112
11 8 6 5 4 2 1 0
2423
2423 ==2 211 +
+2288 +
+2266 +
+2255 +
+2244 +
+2222 +
+2211 +
+2200 =
= 100101110111
10010111011122
11
2423
That is, to convert = 2 +
a decimal 2 + 2 + 2 + 2 + 2 + 2 + 2 = 100101110111
2423 = 211 +number
28 + 2to6 a binary
+ 25 + 24number
+ 22 +you21 all
+ 2the
0 time subtracts the 2maximum
= 1001011101112
That
Thatofis,
power to
to convert
is,2 and continue
convert aa until
decimal
younumber
decimal get 0 or to
number 1. aa binary
to binary number
number you
you all
all the
the time
time subtracts
subtracts the
the maximum
maximum
That
power is,
of to
2 convert
and a
continuedecimal
until number
you get 0 to
or a
1. binary number you all the time subtracts the maximum
power
That of 2toand
That is,
is, continue
convert
convert until you
a adecimal
decimal get
number 0 orto1.atobinary
number number you all the time subtracts the maximum
power
Below is of 2 and
another continue
example: until you get 0 or 1. a binary number you all the time subtracts the
power of 2 power
maximum and continue
of 2 anduntil continue
you get 0 or 1. you get 0 or 1.
until
Below
Below is is another
another example:
example:
Below is another example:
Below is another example:

112
112
112
112
112
164
JAVA 5: FILES AND JAVA IO FInal example

That is, to convert a decimal number to a binary number you all the time subtracts the
JAVA 5: FILES AND JAVA IO Final example
maximum power of 2 and continue until you get 0 or 1.

Below
Below is
is another
another example:
example:

265 = 2288 +
265 = = 2288 +
+ 99 = + 2233 +
+ 11 =
= 100001001
10000100122

The
The method
The method
methodis
method isis basically
isbasically
basically
basically simple,
simple, butbut
but
simple,
simple, in
but in
in practice
in practice and
practice
practice and
and especially
and especially for for
for large
especially
especially large
large numbers,
fornumbers,
large numbers, itit can
can be
numbers, itit can
can be
be difficult
difficult to
be
to
determine
determineto
difficult
difficult tothe
the powers
powers of
determine
determine 22 that
ofthe
the that you
you needs.
powers
powers of 22 Below
needs.
of Below
that is
is aaneeds.
that you
you little
little more
needs. more
Below
Belowdirect
is aaway,
direct
is way, where
where
little
little more
more you
you constantly
constantly
direct
direct way,
way,
divide
where
where by
divide you
by 2:
you2:constantly
constantly divide
divide by by 2:
2:

265 : 100100001
265 :: 100100001
265 100100001
132
132
132
66
66
66
33
33
33
16
16
16
88
8
44
4
2
22
1
11
0
00

265 10 =
26510 = 100001001
10000100122

You
You divide
divide by
by 22 (equivalent
(equivalent to to halving
halving the
the number),
number), andand you
you continues
continues with
with that
that until
until the
the result
result is
is 0.
0. In
In
each
each division
division there
there isis aa residue
residue that
that is
is either
either 00 or
or 1.
1. This
This residue
residue is
is written
written after
after the
the colon.
colon. When
When
finished
finished -- quotient
quotient isis 00 -- the
the bits
bits after
after the
the colon
colon is
is the
the binary
binary representation
representation in
in reverse
reverse order
order -- that
that is
is the
the
most
most significant
significant bit
bit at
at the
the end.
end.

This
This method
method is
is really
really not
not so
so much
much simpler
simpler than
than the
the first,
first, the
the division
division may
may be
be long,
long, but
but the
the operations
operations
are
are simple
simple and
and consists
consists of
of determine
determine the
the half
half of
of aa number
number andand where
where the
the remainder
remainder is
is 00 or
or 1.
1.

2423
Need help with your
:: 111011101001
2423 111011101001
1211
1211
605
605
dissertation?
302
302
Get in-depth feedback & advice from experts in your
151
151
topic area. Find out what you can do to improve
75
75 the quality of your dissertation!
37
37
18
18
99
Get Help Now
44
22
11
00

10 2423
2423 =
= 100101110111
10010111011122
Go to www.helpmyassignment.co.uk
10 for more info

Note
Note that
that itit is
is easy
easy to
to calculate
calculate whether
whether the
the result
result is
is correct.
165
correct.

165
33
88
16
16
4
884
2
442
1 5: FILES AND JAVA IO
221 5: FILES AND JAVA IO
JAVA
JAVA Final
FInalexample
example
0
110
00
265
2651010==100001001
10000100122
265
26510 ==100001001
1000010012
10the number), 2 you continues
You
Youdivide
You
You divide
divide
divide by by
by 22(equivalent
by 2(equivalent
2(equivalent
(equivalent totohalving
totohalving
halving the
thenumber),
halving number), and
andyou
the number), continues
youand you with
continues
and withthatthatuntil
continues with
until
withthe
theresult
thatresult
that isis0.0.the
until
until InIn
the
each
result
each division
isis0.
division there
Inthere
each is a residue
isdivision
adivision
residue that
there is
thatthe either
isiseither
is 0
aaresidue or
0 or 1. This
that
1.that residue
iscontinues
This either is
either00is
residue written
oror1.1.This
written after the
residue
after colon. When
isisiswritten
the colon.
Youresult
You divide
divide 0.
by2In
by each
2(equivalent
(equivalent totohalvingthere
halving the residue
number),
number), and
and youis
you continues with thatThis
withthat until residue
untilthe
theresult
result 0.When
iswritten
0.InIn
finished
finished
after -
the quotient
- quotient
colon. is is0
When 0 - -the
thebits
bits after
finished after the
the colon
colon
quotient isisthe
the
is binary
binary
0 representation
representation
the bits after in
in
thereverse
reverse
colon order
order
is - that
-
the that isisthe
binary the
after
each
each the colon.
division
division there
thereisis When
aaresidue finished
residue thatisiseither
that quotient
either 00oror1.is 0This
1.This residue
the
residuebits after
isiswritten
writtenthe colon
after
afterthe is theWhen
thecolon.
colon. binary
When
most
most significant
significant
representation bit
bit at the
atreverseend.
the end.
finished quotientin
- -quotient
representation
finished is0reverse
isin 0- -thethebitsorder
bits afterthe
after
order that
the colon
that isisis
colon thethe
the
is most
thebinary
most
binarysignificant
representation
significant bit
representation bitat
inat the
theend.
inreverse order
end.
reverse order- -that
thatisisthe the
most
mostsignificant
significantbit bitatatthe theend.end.
This
Thismethod
methodisisreally reallynot notsosomuch muchsimpler
simplerthan thanthe thefirst,
first,the
thedivision
divisionmaymaybebelong,long,butbutthetheoperations
operations
This
This method
method isisreally
really not
notsosomuch much simpler
simpler than
thanandthe first,
thewhere the
first,the division
theremainder
divisionis may
may bebelong,
long,but but
are simple
aremethod
simple andand consists
consists ofof determine
determine the half
the half of a
ofthenumber
a number and where maythe remainder 0 or
is 0the 1.
or 1.
This
This
the method
operations isisreally
really
are notnot so
simple somuch
much
and simpler
simpler
consists than
than
of thefirst,
first,
determine the
the division
division
the half may
of be
a be long,
long,
number but
butandthe operations
operations
where the
the operations are simple and consists of determine the half of a number and where the
are simple
simpleand
are
remainder
2423
andisconsists
consistsofofdetermine
is00oror1.1.
:: 111011101001
remainder
2423 111011101001
determinethe thehalfhalfofofaanumber
numberand andwhere
wherethe theremainder
remainderisis00oror1.1.
1211
1211
2423
2423 :: 111011101001
111011101001
605
605 : 111011101001
2423
1211
1211
302
1211
302
605
605
151
605
151
302
302
75
302
75
151
151
151
3737
757575
1818
373737
99
181818
4
9949
2
4424
1
2212
0
1101
00 0
2423
24231010==100101110111
10010111011122
10
2423
242310 ==100101110111
10010111011122
Note
Notethat
thatititisiseasy
easytotocalculate
calculatewhether
whetherthe
theresult
resultisiscorrect.
correct.
Note
Notethat
thatititisisiteasy totocalculate whether the
theresult isiscorrect.
Note
Note that
that iteasy
isiseasy calculate
easy whether
totocalculate
calculate result
whether
whether the
the correct.
result
resultisiscorrect.
correct.

The
The
THE hexadecimal
hexadecimal
THEHEXADECIMAL
HEXADECIMAL system
system
SYSTEM
SYSTEM
With reference to the above it is easy to define
With reference to the 113the hexadecimal system or 16-number system
above it is easy to define 113 the hexadecimal system or 16-numberbecause
system
With
Withreference
referencetotothe
theabove
aboveititisiseasy
easytotodefine
definethe thehexadecimal
hexadecimalsystem
systemoror16-number
16-numbersystem
system because
because
because it is a number
it issystem
a number system where the base or radix is 16, for example
itit
isisaanumber
number system wheresystem
where the
thebase where
base the
ororradix
radix base
isis113
16,
16,for
113
orexample
for radix is 16, for example
example

2
327
3271616==3316
162++2216
16++77==807
8071010

Again,
Again,itititit
Again,
Again, isis
isjust
isjustaaquestion
just
justaquestionofofthe
aquestion
question ofindividual
the
of the symbols
individual symbols
theindividual
individual positions
positions
symbols
symbols means
meanssomething
positions
positionssomething
means different
differentthan
meanssomething
something than ininthe
differentthe
different
decimal system.
decimal system.
than
thanininthe
thedecimal
decimalsystem.
system.
However,
However,there
thereisisone
oneproblem,
problem,since
sincethethe16-number
16-numbersystem
systemrequires
requires16
16symbols,
symbols,and
andfor
forthis
thisapplies
applies
the
the10
10digits
digitsand
andthethefirst
first66letters:
letters:A,A,B,B,C,C,D,D,EEand
andF,F,and
andthe
thesymbols
symbolscan
canthen
thenbebeinterpretated
interpretatedasasinin
the following table:
the following table:

HEX
HEX DEC
DEC BIN
BIN HEX
HEX DEC
DEC BIN
BIN HEX HEX DEC
DEC BIN
BIN HEX
HEX DEC
DEC BIN
BIN
00 00 0000
0000 44 44 0100
0100 88 88 1000
1000 CC 12
12 1100
1100
11 11 0001
0001 55 55 0101
0101 99 99 1001
1001 DD 13
13 1101
1101
22 22 0010
0010 66 66 0110
0110 AA 10
10 1010
1010 EE 14
14 1110
1110
33 33 0011
0011 77 77 0111 166
BB
0111 166 11
11 1011
1011 FF 15
15 1111
1111
With reference
With reference to
to the
the above
above it is easy to define the hexadecimal system or
or 16-number
16-number system
system because
because
With reference
With reference to
to the
the above
above it is easy to define the hexadecimal system or
or 16-number
16-number system
system because
because
itit
it isis
is aaa number
number system
number
system where
system
where the base or radix is 16, for example
where the base or radix is 16, for example
it is a number system where
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example
327
32716 = 3 1622 + 2 16 + 7 = 80710
16 = 3 16 + 2 16 + 7 = 80710
10
10

However,
Again,
Again, itit isthere
is just aa is
just one
one problem,
question since
since the
of the individual 16-number
symbols system
positions requires
meansrequires
something16different
symbols,thanand
in for
the
However,
Again,
Again, itit is just aa question
is there
just
is problem,
question
question
the 16-number system something
of the individual symbols positions means something
16 different
symbols,
something different
than
and
different than
in for
than in
the
in the
the
this applies
decimal
decimal
this system.
system.
applies the
the 10
10 digits
digits and
and the
the first
first 6
6 letters:
letters: A,
A, B,
B, C,
C, D,
D, E
E and
and F,
F, and
and the
the symbols
symbols can
can
decimal system.
decimal system.
then
then be
be interpretated
interpretated as
as in
in the
the following
following table:
table:
However, there
However, there is
is one
one problem,
problem, since the 16-number system requires 16 symbols,
symbols, and
and for
for this
this applies
applies
However, there
However, there is
is one
one problem,
problem, since the 16-number system requires 16 symbols,
symbols, and
and for
for this
this applies
applies
the 10
the 10 digits
digits and
and the
the first
first 6 letters: A, B, C, D, E and F, and the symbols can
can then
then be
be interpretated
interpretated asas in
in
theHEX
the 10 digits
10 digits
DECand
and the
the first
first
BIN 6 letters:
HEX A, B,
DEC C, D, E
BIN and F,
HEXand the symbols
DEC can
can
BIN then
then
HEXbe
be interpretated
interpretated
DEC as
as in
BIN in
the
the following
following table:
table:
the following
the following table:
table:
0 0 0000 4 4 0100 8 8 1000 C 12 1100
HEX
HEX DEC
DEC BIN
BIN HEX
HEX DEC
DEC BIN
BIN HEX
HEX DEC
DEC BIN
BIN HEX
HEX DEC
DEC BIN
BIN
HEX1
HEX DEC
DEC 1 BIN
BIN
0001 HEX
HEX 5 DEC
DEC 5 BIN
BIN
0101 HEX
HEX
9 DEC
DEC
9 BIN
BIN
1001 HEX
HEX
D DEC
DEC
13 BIN
BIN
1101
000 000 0000
0000
0000 444 444 0100
0100
0100
88
88
88
88
1000
1000
1000
C
CC 12
12
12
1100
1100
1100
0 2 0 2 0000
0010 4 6 4 6 0100
0110 1000 CE 12 1100
111 111 0001
0001 555 555 0101
0101 99 A 99 10 1010
1001
1001 DD
14
13
13
1110
1101
1101
1 1 0001
0001 5 5 0101
0101 99 99 1001
1001 DD 13
13 1101
1101
222 3 222 3 0010
0010
0011
0010 666 7 666 7 0110
0110
0111
0110
A
AAB 10
1011
10
1010
1010
1011
1010
EE F
EE
14
14
15
14
1110
1110
1111
1110
2 2 0010 6 6 0110 A 10 1010 14 1110
333 333 0011
0011
0011 777 777 0111
0111
0111
B
BB 11
11
11
1011
1011
1011
FF
FF
15
15
15
1111
1111
1111
3 3 0011 7 7 0111 B 11 1011 15 1111
It is easy to convert a hexadecimal number to the decimal system, and is just a case of
It is easy toto convert
converta ahexadecimal
hexadecimal number to the decimal system,is and is just of
a case of
ItIt
It isis easy
is easy
easy to
to convert aa hexadecimal
convertBelowhexadecimal
number
number
number
to the
to the decimal
to the decimal system,
decimal system, and
system, is just
and is
and just aaa case
just of simple
case of
case simple
simple
It is
simple
simple easy to convert
arithmetic.
arithmetic. a hexadecimal
are some number to
examples:the decimal system, and is just a case of simple
arithmetic.
arithmetic. areBelow
Below are are some examples:
some examples:
examples:
arithmetic. Below
arithmetic. Below are some
Below are some examples:
some examples:

13
13 16 =
1316 163333 +
= 16 + 10 162222 +
10 16 + 3 16 + 14 = 8718
871810
13 16
16 = 16 + 10 16 +33 16
16 +
+ 14
14 =
= 8718 10
871810
10

0032
0032 = 11
16 =
003216 163333 +
11 16 + 3 16 +2 = 720946
72094610
0032 16
16 = 11 16 +33 16
16 +
+ 22 =
= 720946 10
72094610
10

2
2 =2
16 =
216 2 16
16 +
+ 14
14 =
= 46
4610
2 10
16 = 2 16 + 14 = 4610
16


16 ==
= 1010 165555 +
10 16 + 11
11 1616444 +
+ 12
12 16 3 2
3 + 13 162 + 13 16 + 15 = 11292531
+ 13 16 + 15 = 11292531
16 16 3 + 13 16 2 + 13 16 10
16
16 = 10 16 + 11 16 + 12 16 + 13 16 16 + + 15
15 == 11292531
1129253110 10
10
The interesting
The interestingthing thing aboutabout the 16-number
16-number
the 16-number
16-number system system
viewed viewed from
from aa is computer is power
that
that 16 isis
The
The interesting
The interesting
interesting thing
thing
thing about
about
about the the system viewed from
system from aa computer
viewed computer
computer is
is
that
that 16
computer
that 16 is
16 is aais
is a power
power of
of 2:
16
of 2:
2:
The
a interesting
power of 2: thing
16 =about
2 4 the 16-number system viewed from a computer is that 16 is a power of 2:
4 . There and are 16 symbols, and each of these symbols can be precisely
16
a16power
16 ==
= 2 2 .
2...of There
There
There2: 16are
are 16
are =16
symbols,
. There and
162symbols,
each
are each of these
16 symbols, symbols
and each
of these symbols can
can
be
of
be
precisely
these expressed
symbols
precisely
precisely
binary
canbinary
expressed
expressed
with
with 444
be precisely
binary with
16 =
expressed 2 There
binaryare 16
with symbols, and each of these symbols can be precisely expressed binary withto a4a
bits
expressed
bits
bits
(see table
(see
(see
table
table
above).
binary
above).with
above).
This
This
This44 means
bits (see
means
bits (see
that
table
thattable
it is
it
above). This
is extremely
extremely
above). This means
simple
means
simple to
that
that it
to convert
convert
convert
ait
a
is
is extremely
a hexadecimal
extremelynumber
hexadecimal
hexadecimal
simple
simpleto
number
number toto
to
bits
binary
convert (seenumber,table
a above).
then one
hexadecimal This
onenumbermeansto
simply that it iseach
replaces
a binary extremely simple
hexadecimal
number, then to simply
convert
symbol
one witha hexadecimal
its
replaces corresponding
each number
hexadecimal to aa
binary
binary
binary
convertnumber, number,
number,
a hexadecimal then
then one simply replaces each hexadecimal symbol with
with its
its corresponding
corresponding binary
binary
binary
representation as then onenumber
4corresponding
bits: simply to a binary
replaces number,
each then one
hexadecimal simply
symbol replaces
with each hexadecimal
its corresponding binary
symbol
representation
representation with its
as
as 4
4 bits:
bits: binary
symbol with its corresponding binary representation as 4 bits: representation as 4 bits:
representation as 4 bits:
32 = 1010001110110010
16 =
3216
32 10100011101100102
32 22
16 = 10100011101100102

12316 = 0001001000112 = 100100011


123
12316 = 0001001000112 = 100100011222
16 = 0001001000112 = 1001000112
whenpreceded
when precededbyby 0s has
0s has no effect
no effect on theon theofvalue
value of the number.
the number.
when preceded
when
when preceded
precededbyby
by 0s has
0s hashas
0s no effect
no effect on theon theof
value the number.
value of the number.
when preceded by 0s has no effect on the value of the number.
Converting
Convertingthethe
theother
otherwayway- from
frombinary to to
binary hexadecimal
hexadecimal- is similarly
is similarlysimple. TheThe
simple. binary digits
binary are
digits
Converting
Converting
Converting the other
theother way
otherway
way-- from
frombinary to to
binary hexadecimal
hexadecimal- issimilarly simple.
simple.
is similarly The binary
TheThe
simple. binary digits
digits
binary are
are
digits
Converting
arranged the
into other
groups way
of 4 from
bits, andbinary
each tobits
4 hexadecimal
group is - is similarly
converted to simple.
the The binary
corresponding digits are
hexadecimal
are arranged
arranged
arranged into
into groups
into groupsgroups of
of 4 bits,
of 4
andbits, and
each each
4 bits 4 bits
group group
is converted is converted
to the to the
the corresponding
correspondingcorresponding
hexadecimal
hexadecimal
are arranged into groups of 4 bits, and each 4 bits group is converted to the corresponding
arranged into groups of 4 bits, and each 4 bits group is converted to the corresponding hexadecimal
hexadecimal
symbol: symbol:
hexadecimal
symbol: symbol:
114
114
1001110101011110 = 1001110101011110
114 = 95 6
100111010101111022 = 1001110101011110 = 95116

1110000101011 = 1110000101011 = 12
111000010101122 = 1110000101011 = 1216 16

You can thus conclude that conversion between the binary number system and the hexadecimal system
You can thus conclude that conversion between the binary number system and the hexadecimal system
is extremely simple, and in fact it is the same, because the hexadecimal system is merely a shorter
is extremely simple, and in fact it is the same, because the hexadecimal system is merely a shorter
representation of the binary numbers. The binary number system is simple - at least seen from a
representation of the binary numbers. The binary number system is simple - at least seen from a
machine, but for us humans, it is difficult to grasp
167 and remember long sequences of 0 and 1. This is
167
machine, but for us humans, it is difficult to grasp and remember long sequences of 0 and 1. This is
where the hexadecimal system comes into play, as it may represent sequences of 0 and 1 in a short
JAVA 5: FILES AND JAVA IO Final example

You can thus conclude that conversion between the binary number system and the
hexadecimal system is extremely simple, and in fact it is the same, because the hexadecimal
system is merely a shorter representation of the binary numbers. The binary number system
is simple at least seen from a machine, but for us humans, it is difficult to grasp and
remember long sequences of 0 and 1. This is where the hexadecimal system comes into
play, as it may represent sequences of 0 and 1 in a short way that is much easier for us
humans both to read and remember.

Above, I mentioned three number systems and the conversion rules between these systems
can be illustrated as follows:

Brain power By 2020, wind could provide one-tenth of our planets


electricity needs. Already today, SKFs innovative know-
how is crucial to running a large proportion of the
worlds wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

168
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example
JAVA 5: FILES AND JAVA IO FInal example

Here
Here you
Here you should
you should note
should note that
note that III have
that have not
have not shown
not shown any
shown any method
any method to
method to convert
to convert from
convert from decimal
from decimal to
decimal to
to
hexadecimal.
hexadecimal. However,
However, you
you can
can immediately
immediately use
use the
the division
division method,
method, which
which
hexadecimal. However, you can immediately use the division method, which has been used has
has been
been used
used
when
when converting
when converting from
converting from decimal
from decimal to
decimal to binary,
to binary, simply
binary, simply you
simply you must
you must divide
must divide by
divide by 16
by 16 instead
16 instead of
instead of 2.
of 2. In
2. In
In
practice
practice it
practice it may
it may be
may be a bit
be aa bit difficult
bit difficult to
difficult to divide
to divide by
divide by 16
by 16
16 if
if it
if it is
it is done
is done manually
done manually
manually and
and the
and the method
the method
method
has
has only limited interest. Should you convert a decimal number to hexadecimal, it is easiest
has only
only limited
limited interest.
interest. Should
Should you
you convert
convert a
a decimal
decimal number
number to
to hexadecimal,
hexadecimal, it
it is
is easiest
easiest
to
to convert
convert the
the number
number to
to binary
binary and
and from
from there
there to
to a
a hexadecimal
hexadecimal
to convert the number to binary and from there to a hexadecimal number. number.
number.

You
You often
You often hears
often hears that
hears that aaa computer
that computer work
computer work binary,
work binary, and
binary, and what
and what you
what you mean
you mean by
mean by this
by this is,
this is, that
is, that everything
that everything
everything
in
in a computer is represented as binary digits or perhaps more accurately as sequences of
in aa computer
computer is
is represented
represented as
as binary
binary digits
digits
or
or perhaps
perhaps more
more accurately
accurately as
as sequences
sequences of 00
of 0
and
and 1.
1. The
The reason
reason for
for that
that is
is that
that it
it technically
technically is
is simple
simple to
to represent
represent two
two
and 1. The reason for that is that it technically is simple to represent two states in a stable states
states in
in aa stable
stable
and
and simple
and simple manner,
simple manner, for
manner, for example
for example as
example as two
as two voltage
two voltage levels,
voltage levels, 00
levels, 0 volt
volt may
volt may represents
may represents 1,
represents 1, while
1, while the
while the
the
55 volts
5 volts could
volts could mean
could mean
mean 0. 0. The
0. The important
The important thing
important thing is
thing is that,
is that, technically
that, technically
technically it it is
it is easily
is easily separate
easily separate
separate thethe two
the two
two
voltage
voltage levels
levels and
and in
in aa safe
safe way
way to
to determine
determine whether
whether aa unit
unit
voltage levels and in a safe way to determine whether a unit represents 0 or 1. represents
represents 0
0 or
or 1.
1.

Internally
Internally in
Internally in aaa computer
in computer the
computer the smallest
the smallest unit
smallest unit that
unit that directly
that directly can
directly can be
can be accessd
be accessd is
accessd is aaa byte,
is byte, which
byte, which is
which is aaa
is
bit
bit pattern
bit pattern consisting
pattern consisting of
consisting of 88
of 8 bits.
bits. Exactly
bits. Exactly is
Exactly is the
is the machines
the machines RAM
machines RAM memory
RAM memory aaa large
memory large table
large table of
table of 88
of 8 bit
bit
bit
patterns.
patterns. If
If you
you have
have to
to specify
specify the
the exact
exact content
content of
of such
such aa memory
memory cell
cell
patterns. If you have to specify the exact content of such a memory cell in the machines in
in the
the machines
machines
memory,
memory, you
memory, you specify
you specify 88
specify 8 bits,
bits, for
bits, for example
for example
example

01000001
01000001

How
How
How itit it is
is interpreted
is interpreted depends
interpreted depends on
depends on the
on the program
the program that
program that refers
that refers the
refers the storage
the storage cell,
storage cell, but
cell, but interpreted
but interpreted
interpreted
itit
it asas
as aaa binary
binary number,
number, itit
binary number, is
it is the
is the number
the number 65.
number 65. This
65. This number
This number could
number could also
could also be
also be used
be used as
as aaa code
used as code for
code for
for
the
the letter
the letter
letter A, A, and
A, and a program
and aa program could
program could thus
could thus choose
thus choose instead
choose instead of
instead of interpreting
of interpreting the
interpreting the above
the above bit
above bit pattern
bit pattern
pattern
as
as
as anan
an A. A.
A.

A
A computer
A computer will
computer will always
will always internally
always internally represent
internally represent data
represent data as
as aaa bit
data as bit pattern
pattern
bit pattern not
not necessarily
necessarily 88
not necessarily bits,
8 bits,
bits,
but
but often
but often 16
often 16 or
16 or 32,
or 32, and
32, and perhaps
and perhaps even
perhaps even more
even more bits.
more bits. These
bits. These
These bitbit patterns
bit patterns are
patterns are difficult
are difficult to
difficult to handle
to handle
handle
for
for us
for us humans:
us humans: They
humans: They are
They are hard
are hard to
hard to write,
to write, and
write, and they
and they are
they are hard
are hard to
hard to remember.
to remember.
remember. ThisThis
This isis where
is where
where thethe
the
hexadecimal numbers
hexadecimal
hexadecimal numbers come
numbers come in,
come in, that
in, that as
that as the
as the hexadecimal
the hexadecimal numbers
hexadecimal numbers in
numbers in reality
in reality is
reality is just
is just aaa short
just short
short
representation
representation of
representation of binary
of binary numbers,
binary numbers,
numbers, so so they
so they are
they are often
are often chosen
often chosen
chosen toto show
to show the
show the binary
the binary values
binary values for
values for
for
us
us people
us people in
people in hexadecimal
in hexadecimal form.
hexadecimal form. The
form. The above
The above bit
above bit pattern
bit pattern
pattern maymay also
may also be
also be written
be written
written asas hexadecimal
as hexadecimal
hexadecimal

41
41

As
As aaa further
As further
further example.
example. Consider
Consider the
the number
number

28319
28319
28319

169
169
169
As
As aa further
further example.
example. Consider
Consider the
the number
number

28319
28319
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

If
If you
you converts
converts the
the number
number to
to the
the binary
binary you
you get:
get:
If you converts the number to the binary you get:
28319
28319 :: 111110010111011
111110010111011
14159
28319
14159 : 111110010111011
7079
14159
7079
3539
7079
3539
3539
1769
1769
1769
884
884
884
442
442
442
221
221
221
110
110
110
55
55
55
27
27
27
13
13
13
6
66
3
33
1
11
0
00

28319 10 =
2831910 11011101001111122
10 = 11011101001111122
10

Such a binary
Such number difficult
are difficult to remember and convey
hard to convey to others while its
Such aa binary
binary number
number are
are difficult to
to remember
remember and
and hard
hard to
to convey to
to others
others while
while its
its hexadecimal
hexadecimal
representation
hexadecimal is
representation much
much simpler
simpler to
representation
is is work
to muchwith:
work simpler to work with:
with:

110111010011111
1101110100111112222 =
= 110111010011111
110111010011111 =
= 69
69
69
6916
16
16
16

THE INTEGERS
The
The integers
integers
When introduced to the whole numbers in mathematics, you learn that the whole numbers
is an infinite set. A computer is a machine and on a machine there is nothing that is infinite,
When
When introduced to
introduced it the
the whole
to means whole numbers in mathematics, you
you learn
learn that the whole
whole numbers is
is an
and specifically
infinite set. A computer is a
thatnumbers
machine
that
and
aonina
mathematics,
computer
machine
can
there
represent
is nothing
that
only
that
the
is
ainfinite,
subset numbers
and
the whole an
of specifically
infinite set. A computer is a machine and on a machine there is nothing that is infinite, and specifically
numbers. As mentioned above, the smallest directly addressable unit is a byte consisting of
116
116can represent 2 = 256 different bit patterns,
8 bits. Since a bit can be either 0 or 1, a byte 88

and if you only have 1 byte available, it offers 256 different numbers. It is too little, and
therefore a machine groups several bytes in a word. If you group 2 bytes, wee say that the
unit has a word length of 2 bytes or 16 bits. Similarly, if you group the 4 bytes, you get a
word length of 4 bytes, or 32 bits, and the machine is working with 32-bit integers.

Previously, it was common to use 16-bit integer words, in order to have 16 bits available
to an integer. As long as you talk about non-negative integers, the last 15 bits are used for
the number, while the first is always 0. The number is then represented as a binary number,
and as an example is the number 219 represented as:

0000000011011011

170
170
JAVA
JAVA 5:
JAVA 5: FILES
5: FILES AND
FILES AND JAVA
AND JAVA IO
JAVA IO
IO Final
FInal example
FInal example
example

(you
(you can
(you can easily
can easily calculate
easily calculate that
calculate that it
that itit is
isis the
the number
the number 219).
number 219). As
219). As another
As another example
another example the
example the number
the number 2890
number 2890
2890
is
isis represented
represented as:
represented as:
as:

00000101101001010
00000101101001010

This
This representation
This representation allows
allows to
to represents
represents the
the following
following non-negative
non-negative integers:
integers:

0000000000000000
0000000000000000 00
0000000000000001
0000000000000001 11
0000000000000010
0000000000000010 22
0000000000000011
0000000000000011 33
0000000000000100
0000000000000100 44
....
....
0000000011011011
0000000011011011 219
219
....
....
0111111111111111
0111111111111111 32767
32767

171
171
171
JAVA 5: FILES AND JAVA IO Final example
JAVA
JAVA 5: FILES AND JAVA IO FInal example
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO FInal
FInal example
example
JAVA 5: FILES AND JAVA IO FInal example

That is that the largest positive integer is 32767. Note especially that it is the number
That
That is
is that
that the
the largest
largest positive
positive integer
integer is
is 32767.
32767. Note
Note especially
especially that
that it
it is
is the
the number
number
2That
2
15 is that
and the largest
generally the positive
largest integer
number is 32767.
that can Note
be especially
15 1, and generally the largest number that can be represented by n bits is 2n 1.
1, represented by that
n it
bits is
is the
2 n
number
The
1.
1. The
15 n
215
2 15 1,
1, and
and generally
generally thethe largest
largest number
number that
that can
can be
be represented
represented by by nn bits
bits is
is 22n
n
1. The
The
2 1, and generally
representation of the the largest number
non-negative integers that
on can be represented
aa machine by n bits isand
isis straightforward 2 the
1.only
The
representation
representation
representation of
of
of the
the
the non-negative
non-negative
non-negative integers
integers
integers on
on
on machine
aa machine
machine is
is straightforward
straightforward
straightforward and
and
and the
the
the only
only
only
representation
thing that mattersof the non-negative
is the word length, integers
whichon a machine
determines how is straightforward
large numbers toand thewith.
work only
thing
thing that
that matters
matters is
is the
the word
word length,
length, which
which determines
determines how
how large
large numbers
numbers to
to work
work with.
with.
thing machines
Most that matters is the
today using word length,length
a word whichofdetermines
32 bits forhow large numbers
integers, and it meansto workthatwith.
the
Most
Most machines
machines today
today using
using aa word length of 32 bits for integers, and it means that the
Most machines today using 31 a word length of 32 bits for integers, and it means that
word length of 32 bits for integers, and it means the
largest
largest positive
positive integer
integer isis 2231 = 2147483647 thus well over two billions. As an examplethe
31 = 2147483647 thus well over two billions. As an example is
that is
largest positive
largest positive integer
integer is is 2 231 =
31 = 2147483647
2147483647 thus thus well
well over
over twotwo billions.
billions. As
As anan example
example is is
largest
the positive
number 219 integer is 2 as
represented = 2147483647 thus well over two billions. As an example is
the
the
the number
number 219219 represented
represented as as
the number
number 219219 represented
represented as as
00000000000000000000000011011011
00000000000000000000000011011011
00000000000000000000000011011011
00000000000000000000000011011011

onon
on
on aa machine
machine with
with 32
32 bit
bit words.
words. You
You can
can therefore
therefore see
see the
the advantages
advantages and
and disadvantages
disadvantages of
of
on aa machine
machine with
with 32
32 bit
bit words.
words. You
You can
can therefore
therefore see
see the
the advantages
advantages and
and disadvantages
disadvantages of
of
aaa large
large
large word
word
word length.
length.
length. A
A
A large
large
large word
word
word length
length
length means
means
means the
the
the machine
machine
machine can
can
can work
work
work with
with
with big
big
big numbers,
numbers,
numbers,
a large word length. A large word length means the machine can work with big numbers,
but
but should
but should
but you
should you most
you most
most ofof the
of the time
the time only
time only work
only work on
work on small
on small numbers,
numbers, aaaa large
small numbers, large word
large word length
word length result
length result
result
but should
should you
you most
most ofof the
the time
time only
only work
work on
on small
small numbers,
numbers, a large
large word
word length
length result
result
inin
in
in wasted
wasted
wasted
wasted space,
space,
space,
space, since
since
since
since a large
aaa large
large
large part
part
part
part of
of
of
of the
the
the
the space
space
space
space are
are
are
are just
just
just
just used
used
used
used to
to
to
to 0s.
0s.
0s.
0s.
in wasted space, since a large part of the space are just used to 0s.

Sometimes
Sometimes
Sometimes you
Sometimes you also
also uses
uses double-word
double-word integers,
integers, where
where you
you has
has 64
64 bits
bits available.
available. The
The largest
largest
Sometimes youyou also
also uses
uses double-word
double-word integers,
integers, where
where you
you has
has 64
64 bits
bits available.
available. The
The largest
largest
positive
positive
positive integer
integer isis
positive integer
integer is then
is then
then 9223372036854775807
then 9223372036854775807
9223372036854775807 whose
9223372036854775807 whose binary
whose binary
whose representation
binary representation
binary is:
representation is:
representation is:
is:
positive integer is then 9223372036854775807 whose binary representation is:
0111111111111111111111111111111111111111111111111111111111111111
0111111111111111111111111111111111111111111111111111111111111111
0111111111111111111111111111111111111111111111111111111111111111

And
And
And
And then
then to
then to the
to the negative
the negative numbers,
negative numbers,
numbers, as as
as isis represented
is represented
represented byby their
their 22
by their complement.
2 complement.
complement. For For
For not not having
not having
having
And then
then to
to the
the negative
negative numbers,
numbers, as as is
is represented
represented byby their
their 22 complement.
complement. For For not not having
having
to
to
to
to write
write
write too
too long
long bit
bit patterns,
patterns, III will
will start
start with
with aaa word
word length
length of
of 88 bits,
bits, that
that isis aaa byte.
byte. Note
Note
to write too long bit patterns, I will start with a word length of 8 bits, that is a byte. Note
write too long bit patterns, will start with word length of 8 bits, that is byte. Note
that
that
that the
the
the largest
largest
largest positive
positive
positive integer
integer
integer that
that
that can
can
can be
be
be represented
represented
represented in
in
in one
one
one byte
byte
byte isis
is
that the largest positive integer that can be represented in one byte is
01111111 = 127
=
01111111
01111111 =
= 127
127

Consider as
Consider as
Consider
Consider an
as an example
an example the
example the number
the number 97,
number 97, and
97, and in
and in one
in one byte
byte itit
one byte it isis represented
is represented as
represented as the
as the binary
the binary
binary
Consider as
as an
an example
example the
the number
number 97,
97, and
and in
in one
one byte
byte it
it isis represented
represented as
as the
the binary
binary
number:
number:
number:
number:
number:
01100001
01100001
01100001
01100001

By
By a numbers complement wee means the number obtained by inverting all bits, that is,
By aaa numbers
By numbers complement
numbers complement wee
complement wee means
wee means the
means the number
the number obtained
number obtained by
obtained by inverting
by inverting all
inverting all bits,
all bits, that
bits, that is,
that is,
is,
10011110
10011110
10011110
10011110

This
This operation is seen
seen from
from aaa machine
machine extremely
extremely simple
simple and efficient
and efficient to implement
efficient to implement in
in
This operation
This operation isis
operation is seen
seen from
from a machine
machine extremely
extremely simple
simple and
and efficient
efficient to
to implement
implement in
in
hardware
hardware
hardware and
hardware and
and in
and in
in principle
in principle
principle similar
principle similar
similar to
similar to change
to change
to the
change the
change voltage
the voltage
the level.
voltage level.
voltage level.
level.
hardware and in principle similar to change the voltage level.

172
172
172
172
172
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO Final
FInalexample
example
JAVA 5: FILES AND JAVA IO FInal example

AAA numbers
numbers
numbers 22
2 complement
complement
complement isis
is 11
1 added
added
added toto
to its
its
its complement
complement
complement and
and
and the
the
the 22
2 complement
complement
complement ofof
of 97
97
97
(=(=01100001)
01100001)isisthen:
then:
(= 01100001) is then:

10011110
10011110
1
1
10011111
10011111

That
Thatisis the number -97
-97inin an 8-bit unit
unitisis
That represented by the bit pattern
isthe
thenumber
number-97 inan
an8-bit
8-bitunit isrepresented
representedby
bythe
thebit
bitpattern
pattern

10011111
10011111

ItIt may
Itmay be
maybe noted
benoted that
notedthat adding
adding11
thatadding 1toto
toaaabinary
binary number
binarynumber can
numbercan also
canalso be
alsobe implemented
beimplemented very
implementedvery efficiently
efficientlyinin
veryefficiently in
hardware,
hardware, so the entire operation to determine a numbers 2 complement is highly effective.
hardware,sosothe
theentire
entireoperation
operationtotodetermine
determineaanumbers
numbers22complement
complementisishighly
highlyeffective.
effective.

As another example, consider the number 28, which


whichinin
inaaa8-bit
8-bit unit
unitisis represented
As
Asanother
anotherexample,
example,consider
considerthe
thenumber
number28,
28,which 8-bitunit representedasas
isrepresented as

00011100
00011100

Then the representation


representationofof -28
Then
Thenthe
therepresentation -28is:is:
of-28 is:

11100011
11100011
1
1
11100100
11100100

This calculation may require


require aaa little
little comment about how
how toto
This adds two binary numbers.
This calculation
calculation may
may require little comment
comment about
about how to adds
adds two
two binary
binary numbers.
numbers.
When you adds two decimal numbers, you typical writes the numbers above each other
When
Whenyou youadds
addstwo
twodecimal
decimalnumbers,
numbers,you youtypical
typicalwrites
writesthe
thenumbers
numbersaboveaboveeach othersoso
eachother so
that
that they are aligned with the rear digit. The you adds that the digits from back:
thatthey
theyare
arealigned
alignedwith
withthe
therear
reardigit.
digit.The
Theyou
youadds
addsthat
thatthe
thedigits
digitsfrom
fromback:
back:

1.
1.ifif the sum
sumofof the two digets
digetsisis les than the base 10,
10,itit
itisis
1. the result
ifthe
thesum ofthe
thetwo
twodigets isles
lesthan
thanthe
thebase
base10, isthe
theresult
result
2. else you subtract the base 10 from the sum, and the difference
differenceisis
2. then the result,
2.else
elseyou
yousubtract
subtractthe
thebase
base10
10from
fromthe thesum,
sum,and
andthe
thedifference isthen
thenthe
theresult,
result,
while
while you get a carry on 1, to be included in the sum of the next two digits
whileyouyouget
getaacarry
carryon
on1,1,totobebeincluded
includedininthe
thesum
sumofofthe thenext
nexttwo
twodigits
digits

This method can be applied directly


directlytoto binary numbers (and
(andinin
This principle on any other
Thismethod
methodcancanbe beapplied
applieddirectly tobinary
binarynumbers
numbers(and inprinciple
principleononany
anyother
other
number system), and the difference is only that the base number is now 2: The sum
number
numbersystem),
system),and
andthe thedifference
differenceisisonly
onlythat
thatthe
thebase
basenumber
numberisisnow now2:2:The sumatat
Thesum ataaa
particular position
positionisis either
either000oror
or1,1, and
andisis the sum greater than
than1,1, there will be
beaaacarry
carry
particular
particularposition iseither 1,and isthe
thesum
sumgreater
greaterthan 1,there
therewill
willbe carrytoto
to
the
the next
next position.
position. All
All options
options can
can be
be illustrated
illustrated inin the
the following
following table:
table:
the next position. All options can be illustrated in the following table:

173
173
173
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example

Bit 1 Bit 2 Carry before Sum Carry after

0 0 0 0 0

1 0 0 1 0

0 1 0 1 0

1 1 0 0 1

0 0 1 1 0

1 0 1 0 1

0 1 1 0 1

1 1 1 1 1

It
It is
is thus
thus aa simple
simple matter
matter manually adding binary
manually adding binary numbers.
numbers.

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

174
174
JAVA 5: FILES AND JAVA IO FInal example
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example
JAVA 5: FILES AND JAVA IO FInal example

If you look at the number representation from a computer, it will look at the first bit, and
If
If youyou look
look at
at the
the number
number representation
representation from from aa computer,
computer, itit will will look
look at
at the
the first
first bit,
bit, and
and
Iffromyou thelookvalue
at the
of number representation
this bit know from a or
if is a negative computer, it will look
a non-negative at theand
number, firstis bit,
the and
first
from
from the the value
value of
of this
this bit
bit know
know ifif is is aa negative
negative or
or aa non-negative
non-negative number,number, and
and isis the
the first
first
from
bit 1,thethe value of software
current this bit know
instantlyif isconvert
a negative or a non-negative
the number by take thenumber, and is the
2 complement. first
Actually
bit
bit 1, 1, the
the current
current software
software instantly
instantly convert
convert the
the number
number by by take
take thethe 22 complement.
complement. Actually
Actually
bitit is1,based
the current
on the software
followinginstantly convert the
very important number by
observation thattake the determines
if one 2 complement. Actually2
a numbers
itit is
is based
based onon the
the following
following very very important
important observation
observation thatthat ifif one
one determines
determines aa numbers
numbers 22
itcomplement
is based on and the following
then againvery its 2important
complement observation that if
(thus taking theone determines a twice),
2 complement numbers then2
complement
complement and and then
then again
again its
its 22 complement
complement (thus(thus taking
taking thethe 22 complement
complement twice),
twice), thenthen
complement
you come back andtothen the again
originalits number.
2 complement (thus taking
For example is the the 2 complement
2 complement twice), then
of 28
you
you come come backback to
to the
the original
original number.
number. For For example
example is is the
the 22 complement
complement of of 28
28
you come back to the original number. For example is the 2 complement of 28
11100100
11100100
11100100
and taking the 2 complement to it again, you get:
and
and taking
taking the
the 22 complement
complement to
to itit again,
again, you
you get:
get:
and taking the 2 complement to it again, you get:
11100100
11100100
00011011
11100100
00011011
1
00011011
1
00011100
1
00011100
00011100
that
that isis the
the number
number 28.
28.
that is the number 28.
that is the number 28.
Consider
Consider the the number
number -1.
-1. As
As other
other negative
negative numbers
numbers itit isis represented
represented by
by its
its 22 complement:
complement:
Consider the number -1. As other negative numbers it is represented by its 2 complement:
Consider the number -1. As other negative numbers it is represented by its 2 complement:
00000001
00000001
11111110
00000001
11111110
1
11111110
1
11111111
1
11111111
11111111
That is where all bits is 1.
That is where all bits is 1.
That is where all bits is 1.
That is where all bits is 1.
Consider the bit pattern
Consider the bit pattern
Consider the bit pattern
Consider the bit pattern
10000000
10000000
10000000
that
that ifif interpreted
interpreted as
as aa number
number of
of aa computer
computer will
will be
be interpreted
interpreted as
as aa negative
negative number:
number:
that if interpreted as a number of a computer will be interpreted as a negative number:
that if interpreted as a number of a computer will be interpreted as a negative number:
10000000
10000000
01111111
10000000
01111111
1
01111111
1
10000000
1
10000000
10000000
and
and thus
thus the
the number
number -128.
-128. ItIt means
means that
that with
with aa word
word length
length of
of 88 bits,
bits, the
the computer
computer can
can
and thus the number -128. It means that with a word length of 8 bits, the computer can
work
and with
workthus numbers
withthe numberin
numbers the
the interval
in-128. It means
interval [-128;
that 127],
[-128; 127],awhich
with word has
which has excatly
length of 8256
excatly bits,different
256 integers.
the computer
different can
integers.
work with numbers in the interval [-128; 127], which has excatly 256 different integers.
work with numbers in the interval [-128; 127], which has excatly 256 different integers.

175
175
175
175
JAVA
JAVA
JAVA 5:
5:
5: FILES
FILES
FILES AND
AND
AND JAVA
JAVA
JAVA IO
IO
IO Final
FInal
FInal example
example
example

Note that
Note that the
the interval
interval is
is asymmetric
asymmetric such
such there
there is
is aa negative
negative number
number more
more than
than there
there are
are
positive numbers.
positive numbers. The
The reason
reason is
is that
that there
there must
must also
also be
be room
room to
to the
the number
number 0.
0.

II will
will conclude
conclude the
the examination
examination ofof the
the negative
negative numbers
numbers with
with aa few
few examples.
examples. Consider
Consider
again number
again number 219,
219, which
which in
in aa binary
binary 16-bit
16-bit device
device is
is represented
represented asas

0000000011011011
0000000011011011

The representation
The representation of
of -219
-219 can
can be
be determined
determined as
as

1111111100100100
1111111100100100
1
1
1111111100100101
1111111100100101

In
In aaa 16-bit
In 16-bit device,
16-bit device, -1
device, -1 is
-1 is represented
is represented as
represented as
as

0000000000000001
0000000000000001
1111111111111110
1111111111111110
1
1
1111111111111111
1111111111111111

again only
again only by
by 11 bits.
bits. As
As the
the above
above does
does not
not depend
depend on
on the
the word
word length,
length, you
you may
may notice
notice
that -1 independent of the word length will always be represented as nothing but 1 bits.

Also note
Also note what
what happens
happens ifif you
you calculates
calculates the
the 22 complement
complement of
of 0:
0:

0000000000000000
0000000000000000
1111111111111111
1111111111111111
1
1
0000000000000000
0000000000000000

as
as just
as just again
just again results
again results in
results in 0.
in 0.
0.

Consider
Consider aa 16-bit
16-bit device
device that
that contains
contains the
the number
number 1000000000000000,
1000000000000000, that that is
is where
where the
the
first
first bit
bit is
is 1,
1, but
but the
the rest
rest is
is 0.
0. The
The machine
machine will
will interpret
interpret this
this number
number as
as aa negative
negative number
number
and
and determine
and determine its
determine its 22
its 2 complement:
complement:
complement:

1000000000000000
1000000000000000
0111111111111111
0111111111111111
1
1
1000000000000000
1000000000000000

and
and thus
thus interpret
interpret it
it as
as -32768.
-32768. With
With aaa word
word length
length of
of 16
16 bits
bits you
you can
can represents
represents the
the the
the
and thus interpret it as -32768. With word length of 16 bits you can represents the the
integers in the range [-32768; 32767].
integers in the range [-32768; 32767].

176
176
176
176
JAVA 5:
JAVA 5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final example
FInal example
JAVA 5: FILES AND JAVA IO FInal example

If the
If the word length
length is 32 bits,
bits, the smallest
smallest (negative) number,
number, is
If the word
word length isis 32
32 bits, the
the smallest (negative)
(negative) number, isis

10000000000000000000000000000000
10000000000000000000000000000000

that
thatisisthe
thenumber
number-2147483648,
-2147483648,and andthen
thenyou
youget
getthe
theinterval
interval[-2147483648;
[-2147483648;2147483647].
2147483647].
With a 64-bit word length the interval is [-9223372036854775808; 9223372036854775807].
With a 64-bit word length the interval is [-9223372036854775808; 9223372036854775807].

IfIf you
you look
look atat how
how aa modern
modern computer
computer represents
represents negative
negative integers,
integers, its
its not
not the
the only
only way
way
to
to do it, and there have also been used other methods. Wee uses as mentioned the 22
do it, and there have also been used other methods. Wee uses as mentioned the
complement implemented in hardware,
complement becausebecause itit isis an
an operation
operation that
that can
can be
be effectively
effectively implemented in hardware,
but used only the complement which is even more effective since it
but previously
previously hashas been
been used only the complement which is even more effective since it
simply
simply justjust turns
turns the
the bits.
bits. This
This provides
provides another
another problem,
problem, however.
however. Consider
Consider thethe number
number
00 in an 8-bit device:
in an 8-bit device:

00000000
00000000

IfIf you
you calculates
calculates the
the numbers
numbers complement
complement you
you get
get

11111111
11111111

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

177
177
177
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO Final
FInalexample
example

that
that onon the
the machine
machine vould
vould bebe interpreted
interpreted asas -0,
-0, the
the result,
result, that
that according
according toto the
the basic
basic
math
mathisis0.0.This
Thismeans
meansthatthatwhen
whenyouyouhave
havetwotworepresentations
representationsofofthe thenumber
number0,0,there
thereisis
aaproblem,
problem,which
whichhashastotobe
besolved
solvedininthe
thesoftware,
software,and andthen
thencomplicates
complicatesthethecalculations.
calculations.
ItItisisthe
the reason that computers today anywhere using the 2 complement ratherthan
reason that computers today anywhere using the 2 complement rather thanonly
only
the
thecomplement.
complement.

COMPLEMENT
COMPLEMENTARITHMETIC
ARITHMETIC
The
Thegoal
goalofofthis
thissection
sectionisistotoshow
showhow
howthethecomputer
computerusesusesthe
theabove
abovenumber
numberrepresentation
representation
totocalculations.
calculations. All calculations are performed by the electronics in your computersprocessor,
All calculations are performed by the electronics in your computers processor,
and
and from manufacturers of processors it is about developing processors that are aseffective
from manufacturers of processors it is about developing processors that are as effective
asaspossible,
possible,but
butalso
alsototoaacompetitive
competitiveininprice.
price.

ADDITION
ADDITION
AAprocessor
processormust
mustbe beable
abletotoperform
performmultiple
multipleoperations,
operations,butbutthethemain
mainthing
thingisistotoadd
addtwo
two
integers. This section will be based on a processor that can perform addition
integers. This section will be based on a processor that can perform addition of two binaryof two binary
numbers,
numbers,and andletletme
mebegin
beginbybyare
arefew
fewexamples
examplestotoillustrate
illustratewhatwhatcan
canbebedone
doneby byaddition
addition
ofoftwo
twobinary
binarynumbers.
numbers.Basically,
Basically,I Iwill
willcount
counton on88bits.
bits.ItItisissomething
somethingofofaasimplification,
simplification,
but
butsince
sinceititdoes
doesnot
notchange
changeanything
anythingfor forthe
thebasics,
basics,ititmeans
meansthatthatI Ican
canillustrate
illustrateititall
all
with fewer bits.
with fewer bits.

First,
First,recall
recallthat
thatwith
with88bits,
bits,only
onlythe
theinterval
interval[-128;
[-128;127]
127]are
areprovided.
provided.

Calculate
Calculate73
73++46
46

The
Theprocessor
processormust
mustthen
thenadds
addsthe
thetwo
twobinary
binarynumbers
numbers01001001
01001001and
and00101110:
00101110:

00010000
01001001
00101110
01110111

whereinthe
wherein thetop
toprow
rowofofbits
bitsisisthe
thecarry.
carry.ItItisiseasy
easytotofigure
figureout
outthat
thatthe
theresult
resultisisthe
thenumber
number
119,which
119, whichisisalso
alsothe
thecorrect
correctresult.
result.

Calculate11++22
Calculate

178
178
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO Final
FInalexample
example
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO FInal
FInal example
example

This
Thisisisaasimple
simplecalculation
calculationand
andthe
theresult
resultmust
mustbe
be3:3:
This is a simple calculation and the result must be 3:

00000000
00000000
00000000
00000001
00000001
00000001
00000010
00000010
00000010
00000011
00000011
00000011

Calculate112
Calculate 112 + (-43)
Calculate 112++(-43)
(-43)

112 = 01110000
112
112 = = 01110000
01110000
43 = 00101011
43 = 00101011
43 = 00101011

The 2 complement of 43:


The22complement
The complementofof43:
43:

00101011
00101011
00101011
11010100
11010100
11010100
1
1
1
11010101
11010101
11010101

-43==11010101
-43 11010101 andthe
the processormust
must thereforeadd
add thenumbers
numbers 01110000and
and 11010101:
-43 = 11010101and
and theprocessor
processor musttherefore
therefore addthe
the numbers01110000
01110000 and11010101:
11010101:

11100000
11100000
11100000
01110000
01110000
01110000
11010101
11010101
11010101
01000101
01000101
01000101

Thismeans
This means thatyou
you getaaresult
result thatcan
can quicklybe
be convertedtoto69,
69, whichisisthe
the correctresult.
result.
This meansthat
that youget
get a resultthat
that canquickly
quickly beconverted
converted to 69,which
which is thecorrect
correct result.

Perhapsititisisnot
Perhaps not entirelyobvious,
obvious, forififyou
you manualdo do theabove
above additionyouyou willsee
see that
Perhaps it is notentirely
entirely obvious,for
for if youmanual
manual dothe the aboveaddition
addition youwillwill seethat
that
thereisisaacary
there carythe
thelast
lasttime,
time,who
whoapparently
apparentlyjust
justdisappears
disappearsand
andactually
actuallyititdo,
do,because
becausethere
there
there is a cary the last time, who apparently just disappears and actually it do, because there
isis noroom
isno
room forit.it.You
no roomfor
You cansay
for it. Youcan
say thatyou
can saythat
you dropsaasign
that youdrops
sign bitaway
drops a signbit
away becausethe
bit awaybecause
the resultwas
because theresult
was positive.
result waspositive.
positive.

Sowe
So we cannote
note thataaprocessor
processor maywell
well addaapositive
positive andaanegative
negative number.
So wecan
can notethat
that a processormay
may welladd
add a positiveand
and a negativenumber.
number.

Calculate43
Calculate 43 + (-112)
Calculate 43++(-112)
(-112)

112 = 01110000
112
112 = = 01110000
01110000
43 = 00101011
43 = 00101011
43 = 00101011

179
179
179
179
JAVA
JAVA5:
JAVA 5:5:FILES
FILESAND
FILES ANDJAVA
AND JAVAIO
JAVA IO
IO Final
FInalexample
FInal example
example

The
The22complement
complementtoto112:
112:

01110000
01110000
10001111
10001111
11
10010000
10010000

-112
-112=
-112 ==1001000
1001000and
1001000 andthe
and theprocessor
the processormust
processor musttherefore
must thereforeadd
therefore addthe
add thenumbers
the numbers1001000
numbers 1001000and
1001000 and00101011:
and 00101011:
00101011:

00000000
00000000
10010000
10010000
00101011
00101011
10111011
10111011

When
Whenthe
When thefirst
the firstbit
first bitis
bit isis1,
1,1,the
theresult
the resultis
result isisnegative
negativeand
negative andyou
and youhave
you haveto
have todetermine
to determinethe
determine the2
the 22complement:
complement:
complement:

10111011
10111011
00000100
00000100
11
01000101
01000101

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

180
180
180
180
JAVA 5: FILES AND JAVA IO FInal example
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

It is the number 69, and then the result is -69, which is also correct.
It is the number 69, and then the result is -69, which is also correct.

Calculate 73 + 60
Calculate 73 + 60
73 = 01001001
73 = 01001001
60 = 00111100
60 = 00111100

The processor must calculate the sum of 01001001 and 00111100:


The processor must calculate the sum of 01001001 and 00111100:
11110000
11110000
01001001
01001001
00111100
00111100
10000101
10000101

The result is negative, then you have to determine the complement


The result is negative, then you have to determine the complement
10000101
10000101
01111010
01111010
1
1
01111011
01111011

Converted to decimal it will be the result -123, which is obviously wrong. What you see
Converted to decimal it will be the result -123, which is obviously wrong. What you see
here is an example of an overflow: The sum of the two numbers can not be in an 8-bit
here is an example of an overflow: The sum of the two numbers can not be in an 8-bit
device and fall outside the range that can be represented with 8 bits. Note that, when the
device and fall outside the range that can be represented with 8 bits. Note that, when the
addition of the last two digits there was a cary, which was discarded.
addition of the last two digits there was a cary, which was discarded.

Usually makes a processor nothing in such a situation beyond that it delivers a wrong result.
Usually makes a processor nothing in such a situation beyond that it delivers a wrong result.
If it is desired to handle this situation, it is up to the software, testing for overflow. If the
If it is desired to handle this situation, it is up to the software, testing for overflow. If the
processor had to do something, it would be more complex, and it would cost in efficiency
processor had to do something, it would be more complex, and it would cost in efficiency
and it is also not so easy to determine what the processor where appropriate should do. It
and it is also not so easy to determine what the processor where appropriate should do. It
is not entirely true that the processor is not doing anything. After each addition sets the
is not entirely true that the processor is not doing anything. After each addition sets the
processor some status bits, and one of them says, there has been an overflow. There is also
processor some status bits, and one of them says, there has been an overflow. There is also
a status bit, which is the last cary and software can thus test whether there is a cary which
a status bit, which is the last cary and software can thus test whether there is a cary which
is thrown away.
is thrown away.

It is worth emphasizing that the problem of overflow is not specifically associated with a
It is worth emphasizing that the problem of overflow is not specifically associated with a
word length of 8, but it can occur regardless of the word length used. It is only a question
word length of 8, but it can occur regardless of the word length used. It is only a question
of adding two numbers that are sufficiently large.
of adding two numbers that are sufficiently large.

181
181
181
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

32
32 BITS
BITS ADDITION
ADDITION
As
As aa final
final example,
example, II look
look at
at addition
addition of
of two
two numbers,
numbers, butbut this
this time
time with
with aa word
word length
length of
of
32
32 bits,
bits, which
which better
better reflects
reflects what
what happens
happens in
in aa real
real processor.
processor. II will
will look
look at
at the
the calculation
calculation

2819316
2819316 +
+ 32512819
32512819

Actually
Actually there
there is
is nothing
nothing new
new in
in relation
relation to
to the
the above,
above, except
except that
that II should
should write
write more
more bits.
bits.

First
First aa converting:
converting:

2819316 = 2B04F4 = 00000000001010110000010011110100


32512819 = 1F01B33 = 00000001111100000001101100110011

Then the calculation:

360
.
00000011110000000011111111100000

thinking
00000000001010110000010011110100
00000001111100000001101100110011
00000010000110110010000000100111

360
thinking . 360
thinking .
Discover the truth at www.deloitte.ca/careers Dis

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


182
182
JAVA
JAVA5:
5:FILES
FILESAND
ANDJAVA
JAVAIOIO Final
FInalexample
example
JAVA 5: FILES AND JAVA IO FInal example

And
Andso
And soconverting
so convertingthe
converting theresult:
the result:
result:

00000010000110110010000000100111 == 0000|0010|0001|1011|0010|0000|0010|0111
00000010000110110010000000100111 0000|0010|0001|1011|0010|0000|0010|0111
== 021B2027
021B2027
= 35332135
= 35332135

and
anditititisisiseasy
easytotocalculate
calculatethat
thatthe
theresults
resultsisisiscorrect.
correct.
and easy to calculate that the results correct.

SUBTRACTION
SUBTRACTION
SUBTRACTION
IfIfwe
wenow
nowhave
haveaaamachine
machine(a(a (aprocessor)
processor)which
whichadds,
adds,you
youalso
alsohas
hasaaamachine
machinethatthatcan
cansubtract.
subtract.
If we now have machine processor) which adds, you also has machine that can subtract.
Should you
Should you subtract
you subtract two
subtract two numbers,
two numbers, simply
numbers, simply adding
simply adding the
adding the second
the second numbers
second numbers 2 complement
complementto
numbers 22 complement to
Should to
the first,
the first, and
first, and really
and really its
really its nothing
its nothing more
nothing more than
more than to
than to exploit
to exploit one
exploit one of
one of the
of the rules
the rules in
rules in maths:
in maths:
maths:
the

aabb==aa++((b)b)
a b = a + ( b)

IfIfwe
weagain
againhave
haveaaaword
wordlength
lengthofof888bits,
bits,and
andifififyou
youhave
havetotocalculate
calculate83
8323
23the
thefollowing
following
If we again have word length of bits, and you have to calculate 83 23 the following
happens when
happens when you
when you have
you have to
have to calculate
to calculate the
calculate the sum
the sum 83
sum 83 + (-23)
83 ++ (-23)
(-23)
happens

83
83 == 01010011
01010011
23
23 == 00010111
00010111

Thecomplement
The
The complementof
complement of23:
of 23:
23:

00010111
00010111
11101000
11101000
11
11101001
11101001

-23 == 11101001
-23 11101001

10000110
10000110
01010011
01010011
11101001
11101001
00111100
00111100

The
Theresult
The resultisisis00111100
result 00111100===60.
00111100 60.
60.

As
Asanothe
As anotheexample:
anothe example:Calculate
example: Calculate2819316
Calculate 281931632512819,
2819316 32512819,when
32512819, whenthe
when theword
the wordlength
word lengthisisis32
length 32bits:
32 bits:
bits:

2819316
2819316 == 2B04F4
2B04F4 == 00000000001010110000010011110100
00000000001010110000010011110100
32512819
32512819 1F01B33 ==
== 1F01B33 00000001111100000001101100110011
00000001111100000001101100110011

183
183
183
JAVA
JAVA
JAVA 5:
5:
5: FILES
FILES
FILES AND
AND
AND JAVA
JAVA
JAVA IO
IO
IO Final
FInal
FInal example
example
example
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO FInal
FInal example
example

The
The
The complement
complement to
to 32512819:
32512819:
The complement
complement to
to 32512819:
32512819:
00000001111100000001101100110011
00000001111100000001101100110011
00000001111100000001101100110011
00000001111100000001101100110011
11111110000011111110010011001100
11111110000011111110010011001100
11111110000011111110010011001100
11111110000011111110010011001100
1
1
1
1
11111110000011111110010011001101
11111110000011111110010011001101
11111110000011111110010011001101
11111110000011111110010011001101

That
That isis
That
That is
is
-32512819
-32512819 =
= 11111110000011111110010011001101
-32512819 = 11111110000011111110010011001101
-32512819 = 11111110000011111110010011001101
11111110000011111110010011001101

Calculation:
Calculation:
Calculation:
Calculation:
00000000000111100000100111111000
00000000000111100000100111111000
00000000000111100000100111111000
00000000000111100000100111111000
00000000001010110000010011110100
00000000001010110000010011110100
00000000001010110000010011110100
00000000001010110000010011110100
11111110000011111110010011001101
11111110000011111110010011001101
11111110000011111110010011001101
11111110000011111110010011001101
11111110001110101110100111000001
11111110001110101110100111000001
11111110001110101110100111000001
11111110001110101110100111000001

The
The
The complement of
complement of the
the result:
result:
The complement
complement of
of the
the result:
result:
11111110001110101110100111000001
11111110001110101110100111000001
11111110001110101110100111000001
11111110001110101110100111000001
00000001110001010001011000111110
00000001110001010001011000111110
00000001110001010001011000111110
00000001110001010001011000111110
1
1
1
1
00000001110001010001011000111111
00000001110001010001011000111111
00000001110001010001011000111111
00000001110001010001011000111111

and
and
and the
the result:
result:
and the
the result:
result:
00000001110001010001011000111111
00000001110001010001011000111111 = 0000|0001|1100|0101|0001|0110|0011|1111
= 0000|0001|1100|0101|0001|0110|0011|1111
00000001110001010001011000111111
00000001110001010001011000111111 =
= 0000|0001|1100|0101|0001|0110|0011|1111
0000|0001|1100|0101|0001|0110|0011|1111
=
= 01C5163F
= 01C5163F
= 01C5163F
01C5163F
=
= 29693503
29693503
=
= 29693503
29693503

The
The result
result is asas follows,
follows, and
and itit is easy
easy to
to calculate
calculate that
that itit is correctly:
correctly:
The result isis
The result is asas follows,
follows, and
and it
it isis
is easy
easy to
to calculate
calculate that
that it
it isis
is correctly:
correctly:
-29693503
-29693503
-29693503
-29693503

The arithmetic
The arithmetic asas outlined
outlined in in this
this section
section isis
is called
called complement
complement arithmetic,
arithmetic, and
and as
as you
you can
can
The arithmetic
The arithmetic asas outlined
outlined in in this
this section called complement
section is called complement arithmetic,
arithmetic, and
and as
as you
you can
can
see,
see,
see, it
it
it is
is
is sufficient
sufficient
sufficient to
to
to construct
construct
construct aa
a processor
processor
processor that
that
that can
can
can add.
add.
add. Then
Then
Then at
at
at the
the
the same
same
same time
time
time aa
a processor
processor
processor
see, it is sufficient to construct a processor that can add. Then at the same time a processor
also
also can
can subtract.
subtract. This
This is the
the reasons
reasons to
to implements
implements the the representation
representation ofof negative
negative numbers
numbers
also
also can
can subtract. This isis
subtract. This is the
the reasons
reasons to
to implements
implements the the representation
representation ofof negative
negative numbers
numbers
by
by
by their
their 2
2 complement.
complement.
by their
their 22 complement.
complement.

184
184
184
184
184
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example
JAVA 5: FILES AND JAVA IO FInal example

MULTIPLICATION
MULTIPLICATION
If
If you
you in
in the
the decimal
decimal number
number system
system multiply
multiply aa number
number byby 10
10 (with
(with the
the base),
base), you
you must
must
move
move the number one position to the left and then add a 0. The same is valid for the
the number one position to the left and then add a 0. The same is valid for the
binary number system: If you have to multiply a number by 2, you must
binary number system: If you have to multiply a number by 2, you must move the bits move the bits
one
one position
position to
to the
the left
left and
and adding
adding aa 00 and
and such
such an
an operation
operation is
is called
called aa left
left shift,
shift, and
and it
it is
is
an operation which is simple to implement in hardware. Consider again
an operation which is simple to implement in hardware. Consider again the number 219:the number 219:

0000000011011011
0000000011011011

If
If you
you perform
perform aa left
left shift
shift on
on this
this number
number you
you will
will get:
get:

0000000110110110
0000000110110110

and
and aa simple
simple calculation
calculation shows
shows that
that it
it is
is number
number 438
438 corresponding
corresponding to
to aa left
left shift
shift is
is
multiplying by 2.
multiplying by 2.

If
If you
you look
look at
at how
how toto perform
perform multiplication
multiplication in
in the
the 10-number
10-number system,
system, for
for example.
example.
432
432 * 1322, so this is done by multiplying the
* 1322, so this is done by multiplying the 1322
1322 first with 2, then by 3 and finally
first with 2, then by 3 and finally
with 4, but such that you each time shifts 1322
with 4, but such that you each time shifts 1322 aa position
position left and finally adds to it all:
left and finally adds to it all:

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

185
185
185
JAVA 5: FILES AND JAVA IO FInal example
JAVA 5: FILES AND JAVA IO FInal example
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example
432
432 ** 1322
1322
022100
022100
432 * 1322
2644
2644
022100
39660
39660
2644
528800
528800
39660
571104
571104
528800
571104
The
The same
Thesame method
samemethod
methodcancan
canbe be applied
beapplied to
appliedto the
tothe binary
thebinary numbers,
binarynumbers,
numbers,but but just
butjust simpler,
justsimpler, because
simpler,because every
becauseevery time
everytimetime
either
The same
either
either multiply
multiply
multiply by
method
by 0 or
by00can 1:
be
oror1:1:
ToTo
To multiply
applied
multiply
multiply by
tobythe0 gives
binary 0, and multiplying
gives0,0,numbers,
by00gives and but justby
andmultiplying
multiplying by
by 1 gives
simpler,
11gives the number
because
givesthe every
thenumber
number again.
time
again.
again.
either multiply by 0 or 1: To multiply by 0 gives 0, and multiplying by 1 gives the number again.
Suppose
Suppose
Supposeyouyou want
youwant to
wantto multiply
tomultiply 219
multiply219
219byby 38,
by38, which
38,which have
whichhave the
havethe binary
thebinary values
binaryvalues 11011011
values11011011
11011011and and 100110.
and100110.
100110.
If
IfIf the
Suppose
the multiplication
themultiplication
multiplication is carried
you want toisismultiply
carried out
219
carriedout
out with
with
with a word
by a38, which
aword
word length
length
length of
haveofof
the
1616 bits,
16binary it may
bits,ititvalues
bits, may
maybebebe performed
11011011
performed
performed andas follows:
100110.
asasfollows:
follows:
If the multiplication is carried out with a word length of 16 bits, it may be performed as follows:
100110
100110 ** 0000000011011011
0000000011011011
0000010010000000
0000010010000000
100110 * 0000000011011011
0011110110111000
0011110110111000
0000010010000000
0000000110110110
0000000110110110
0011110110111000
0000001101101100
0000001101101100
0000000110110110
0001101101100000
0001101101100000
0000001101101100
0010000010000010
0010000010000010
0001101101100000
0010000010000010
where
where I have only included the subresults which do not give 00 there are three such
where II havehave only
only included
included the the subresults
subresults which
which do do not
not give
give 0 there
there are
are three
three such
such
subresults
subresults
where I have to
to calculate
calculate the
the
only included sum,
sum, as
as there
there are
are
theas subresults three
three 11 bits
which1 dobits in
in the
the number
number 100110.
100110. The
The result
result
subresults to calculate the sum, there are three bitsnot givenumber
in the 0 there are three
100110. such
The result
isissubresults
the
the number
number 8322.
8322.
to calculate
is the number 8322. the sum, as there are three 1 bits in the number 100110. The result
is the number 8322.
ItIt isis somewhat difficult to perform this multiplication manually, as by adding several binary
It is somewhat
somewhat difficult
difficult toto perform
perform thisthis multiplication
multiplication manually,
manually, as as by
by adding
adding several
several binary
binary
numbers
numbers you
you
It is somewhat need
need to
to be
difficult be more
more careful
careful to
to note
note what
what you
you have
have in
in carry.
carry.
numbers you need to betomore
perform this to
careful multiplication
note what you manually,
have inascarry.
by adding several binary
numbers you need to be more careful to note what you have in carry.
As
As another example, I calculate the product 752 * 41 in a 16-bit device:
As another
another example,
example, II calculate
calculate the
the product
product 752752 ** 41
41 inin aa 16-bit
16-bit device:
device:
As another example, I calculate the product 752 * 41 in a 16-bit device:
752
752 == 1011110000
1011110000
41 = 101001
41 == 101001
752 1011110000
41 = 101001
101001
101001 ** 0000001011110000
0000001011110000
0000100000000000
0000100000000000
101001 * 0000001011110000
0011101100000000
0011101100000000
0000100000000000
0000001011110000
0000001011110000
0011101100000000
0001011110000000
0001011110000000
0000001011110000
0101111000000000
0101111000000000
0001011110000000
0111100001110000
0111100001110000
0101111000000000
0111100001110000
that
thatisisisthe
that the number
thenumber
number30832.30832.
30832.
that is the number 30832.
In practice,
practice,itititisisisnot
InInpractice, not so
notso important
soimportant
importanttoto be
tobe able
beable to
ableto multiply
tomultiply binary,
multiplybinary, but
binary,but the
butthe important
theimportant thing
thingisisis
importantthing
that
that the
the
In practice,
that multiplication
themultiplication
it is not socan
multiplication can be
be performed
beperformed
important
can only
only
to be able
performed by
by
onlyto the
the two
thetwo operations,
twooperations,
bymultiply binary, left
but left
operations, shift
leftshift
the and
shiftand addition
andaddition
important thing is
addition
and,
and,
that therefore,
and,therefore,
the can
can
multiplication
therefore, be
canbe carried
becarried
carried out
can beout by
outby a processor
byaaprocessor
performed which
only bywhich
processor the
which can
can
two shift
shift and
shiftand
operations,
can add.
add.
andleftadd.shift and addition
and, therefore, can be carried out by a processor which can shift and add.

186
186
186
186
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

DIVISION
DIVISION

Division isis performed


Division performed inin the
the decimal
decimal number
number system
system by
by subtraction.
subtraction. The
The division
division algorithm
algorithm
can also
can also be
be transferred
transferred to
to the
the binary
binary number
number system,
system, and
and division
division can
can then
then be
be performed
performed
by the
by the processor,
processor, which
which can
can add.
add.

ItIt isis not


not so
so easy
easy to
to divide
divide manually
manually because
because you
you have
have to
to keep
keep track
track of
of whether
whether you
you have
have
to borrow,
to borrow, but
but one
one example.
example.

Consider
Consider thethe number
number 1355613556 and
and assume
assume that
that itit must
must be be divided
divided byby 38,
38, and
and the
the use
use of
of aa
word length
word length of
of 1616 bits.
bits. Note
Note first
first that
that the
the result
result isis an
an integer,
integer, and
and aa simple
simple calculation
calculation says
says
that the
that the result
result should
should be be 356:
356:

38 | 13556 | 356
114..
215.
190.
256
228
28

The
The quotient
quotient isis 356,
356, and
and you
you get
get aa remainder
remainder of
of 28,
28, corresponding
corresponding to
to the
the division
division does
does
not go up.
not go up.

IfIf you
you attemptes
attemptes to
to copy
copy the
the usual
usual division
division algorithm
algorithm for
for decimal
decimal numbers
numbers to
to the
the binary
binary
system, the method is simpler, since each iteration always results in a 0 time or
system, the method is simpler, since each iteration always results in a 0 time or 1 time. 1 time.

13556 = 11010011110100
38 = 100110

The division
The division can
can now
now be
be done
done binary,
binary, as
as shown
shown below.
below. However,
However, itit isis not
not quite
quite easy
easy to
to
do manually:
do manually:

1. ifif the
1. the number
number youyou divide
divide with
with isis greater
greater than
than the
the number
number above,
above, itit goes
goes aa 00 time,
time,
and the
and the upper
upper number
number goes goes unchanged
unchanged on on to
to the
the next
next step
step
2. otherwise
2. otherwise itit goes
goes aa 11 time,
time, and
and the
the number
number you you divide
divide by,
by, must
must then
then be be subtracted
subtracted
from the
from the number
number above above here
here itit may
may be
be necessary
necessary toto borrow,
borrow, which
which youyou should
should
keep track
keep track of
of
3. the
3. the the
the next
next bit
bit isis used
used (as
(as the
the right
right bit)
bit)
4. continuing
4. continuing until
until there
there are
are no
no more
more bitsbits

187
187
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example

100110 | 0011010011110100 | 00101100100


100110..........
011010.........
100110.........
110100........
100110........
011101.......
100110.......
111011......
100110......
101011.....
100110.....
001011....
100110....
010110...
100110...
101101..
100110..
001110.
100110.
011100
100110
11110

e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili www.discovermitas.com
Maersk.com/Mitas e G
I joined MITAS because for Engine
I wanted real responsibili Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
ree wo
work
or placements ssolve pr

188
188
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example
JAVA 5: FILES AND JAVA IO FInal example

That
That is, the result isis
That is,
is, the
the result
result is

0000000101100100
0000000101100100

that isis the


that the number 356.
356.
that is the number
number 356.

It isis not
It not particularly
It is not particularly interesting
particularly interesting to
interesting to be
to be able
be able to
able to calculate
to calculate binary,
calculate binary, but
binary, but the
but the section
the section shows
section shows that
shows that
that
using
using the
the complement
complement arithmetic
arithmetic and
and a
a processor
processor that
that can
can add
add it
it can
can perform
perform
using the complement arithmetic and a processor that can add it can perform the four the
the four
four
arithmetical operations.
arithmetical operations.
arithmetical operations.

BINARY
BINARY
BINARY OPERATIONS
OPERATIONS
OPERATIONS
Above II have
Above have discussed
Above I have discussed binary
discussed binary arithmetic
binary arithmetic and
arithmetic and explained
and explained why
explained why the
why the addition
the addition isis
addition is aaa fundamental
fundamental
fundamental
operation
operation for a processor. There are other important operations as processors must be
operation for
for a
a processor.
processor. There
There are
are other
other important
important operations
operations as
as processors
processors must
must be able
be able
able
to
to perform
perform all
all of
of which
which can
can be
be implemented
implemented efficiently
efficiently and
and simple
simple in
in hardware.
hardware.
to perform all of which can be implemented efficiently and simple in hardware. This section This
This section
section
lists these
lists these basic binary
binary operations.
lists these basic
basic binary operations.
operations.

Another reason
Another reason for
Another reason for looking
for looking at
looking at these
at these operations
these operations isis
operations is that
that they
that they are
they are supported
are supported by
supported by many
by many programming
many programming
programming
languages,
languages, so the languages has operators that correspond to the binary operations. In
languages, so
so the
the languages
languages has
has operators
operators that
that correspond
correspond to
to the
the binary
binary operations.
operations. In many
In many
many
contexts, itit isis important
contexts, important directly
directly to
to be
be able
able to
to manipulate
manipulate thethe individual
individual bits,
bits, and
and to
to these
these
contexts, it is important directly to be able to manipulate the individual bits, and to these
the
the binary
the binary operators
binary operators are
operators are important.
are important.
important.

LEFT SHIFT
LEFT SHIFT
LEFT SHIFT
This operation
This operation III have
This operation have already
have already mentioned,
already mentioned, but
mentioned, but given
but given aaa device
given device with
device with aaa particular
with particular word
particular word length
word length
length
the
the operation shifts all bits one position to the left and insert a 0 in the right end. For
the operation
operation shifts
shifts all
all bits
bits one
one position
position to
to the
the left
left and
and insert
insert a
a 0
0 in
in the
the right
right end.
end. For
For
example aa 16
example 16 bits
bits unit
unit
example a 16 bits unit

0011101111100001
0011101111100001

and after
and after aaa left
and after left shift
left shift the
shift the value
the value is:
value is:
is:

0111011111000010
0111011111000010

The
The
The bit bit that
bit that was
that was left
left isis
was left gone,
is gone, which
which isis
gone, which is aaa part
part of
part of the
of the operation,
the operation, but
operation, but in
in aaa processor
but in processor this
processor this bit
this bit
bit
is transferred
isis transferred to
transferred to a status
to aa status bit.
status bit.
bit.

If
If the
If the bit
the bit pattern
bit pattern that
that isis
pattern that shifted
is shifted to
shifted to left
to left represents
represents aaa number
left represents number
number itit corresponds
it corresponds to,
corresponds to, that
to, that number
number isis
that number is
multiplied
multiplied
multiplied byby 2.
by 2. Note
2. Note that
Note that this
that this means
this means that
means that if a number
that ifif aa number is shifted
number isis shifted n positions,
shifted nn positions, it corresponds
positions, itit corresponds
corresponds
to,
to, that
to, that the
that the number
the number
number hashas been
has been multiplied
been multiplied by
by 22n..
multiplied by 2nn .

189
189
189
JAVA
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example
JAVA 5:
JAVA 5: FILES
5: FILES AND
FILES AND JAVA
AND JAVA IO
JAVA IO
IO FInal
FInal example
FInal example
example

RIGHT
RIGHT SHIFT
SHIFT
A
A right
right shift
shift is
is an
an operation
operation that
that shifts
shifts all
all the
the bits
bits in
in aa word
word one
one position
position to
to the
the right
right and
and
inserts
inserts aa 00 in
in first
first position,
position, for
for example.
example.

0011101111100001
0011101111100001
0011101111100001

and
and after
after aa right
right shift
shift the
the value
value is
is

0001110111110000
0001110111110000
0001110111110000

If
If the
the bit
bit pattern
pattern that
that is
is shifted,
shifted, represents
represents aa number,
number, it
it means
means that
that the
the number
number is
is divided
divided by
by
2. If the number is shifted n positions, it corresponds to, that the number is divided by 2nnn..
2. If the number is shifted n positions, it corresponds to, that the number is divided by 2 nn

There
There is
is aa variant
variant of
of aa right
right shift,
shift, known
known as as an
an arithmetic
arithmetic right
right shift.
shift. The
The difference
difference isis that
that
the
the bit that is inserted in first position is the sign bit. That is, if the first bit is 0, a 0 bit is
bit that is inserted in first position is the sign bit. That is, if the first bit is 0, a 0 bit is
inserted, and if the first bit is 1, a 1 bit is inserted. If, for example you has the
inserted, and if the first bit is 1, a 1 bit is inserted. If, for example you has the bit pattern bit pattern

0011101111100001
0011101111100001

is
is the
the result
result of
of aa right
right arithmetic
arithmetic shift
shift

0001110111110000
0001110111110000
0001110111110000

an
an such
such the
the same
same as
as aa right
right shift.
shift. If,
If, however,
however, the
the pattern
pattern

1011101111100001
1011101111100001
1011101111100001

is
is the
the result
result of
of aa right
right arithmetic
arithmetic shift
shift

1101110111110000
1101110111110000

190
190
190
190
190
JAVA 5:
JAVA 5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final example
FInal example
JAVA 5: FILES AND JAVA IO FInal example

AND
AND
AND
It is
It is an operation
operation that basically
basically works on
on two bits,
bits, and where
where the result
result is aa 1
1 bit if
if both of
of
It is an
an operation that
that basically works
works on two
two bits, and
and where the
the result is
is a 1 bit
bit if both
both of
the arguments
the arguments are 11 and otherwise
otherwise 0. The
The operation may
may be expressed
expressed in the
the following table:
table:
the arguments are
are 1 and
and otherwise 0.
0. The operation
operation may be
be expressed in
in the following
following table:

Arg
Arg 1
1 Arg
Arg 2
2 AND
AND
0
0 0
0 0
0
0
0 1
1 0
0
1
1 0
0 0
0
1
1 1
1 1
1

The
The operation
operation corresponds
corresponds to
to aa conjunction
conjunction of
of two
two statements.
statements.

If
If you
you have
have two
two words
words an
an AND
AND of
of the
the two
two words,
words, is
is aa bitwise
bitwise AND.
AND. If,
If, for
for example
example you
you
has
has two
two 8-bit
8-bit words:
words:

01100010
01100010
11110000
11110000

191
191
191
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example
JAVA 5:
JAVA 5: FILES AND
AND JAVA IO
IO FInal example
example
JAVA 5: FILES
FILES AND JAVA
JAVA IO FInal
FInal example

you
you determines
determines their
their AND
AND as
as follows:
follows:
you
you determines
determines their
their AND
AND as
as follows:
follows:
01100010
01100010
01100010
01100010
11110000
11110000
11110000
11110000
AND 01100000
AND 01100000
AND 01100000
AND 01100000

That
That is, you
is, you get
get 1,
1, where
where there
there are
are two
two 11 bits, and
bits, and otherwise
otherwise the
the 0.
0.
That
That is,
is, you
you get
get 1,
1, where
where there
there are
are two
two 11 bits,
bits, and
and otherwise
otherwise the
the 0.
0.
OR
OR
OR
OR
It isis an
It an operation
operation that
that basically
basically works
works on
on two
two bits,
bits, and
and the
the result
result isis aa bit,
bit, which
which isis 00 ifif both
both
It
It is
is an
an operation
operation that
that basically
basically works
works on
on two
two bits,
bits, and
and the
the result
result is
is aa bit,
bit, which
which is
is 0
0 if
if both
both
arguments are
arguments are 00 and
and otherwise
otherwise isis 1.
1.
arguments are 0 and otherwise
arguments are 0 and otherwise is 1. is 1.

The
The operation may
operation may be
be expressed
expressed in
in the
the following
following table:
table:
The
The operation
operation may
may be
be expressed
expressed in
in the
the following
following table:
table:

Arg 1 Arg 2 OR
Arg 1
Arg 1 Arg 2
Arg 2 OR
OR
Arg 1 Arg 2 OR
0 0 0
0
0 0
0 0
0
0 0 0
0 1 1
0
0 1
1 1
1
0 1 1
1 0 1
1
1 0
0 1
1
1 0 1
1 1 1
1
1 1
1 1
1
1 1 1

The operation corresponds to a disjunction of two statements.


The
The operation
The operation corresponds
operation corresponds to
to aaa disjunction
corresponds to disjunction of
disjunction of two
of two statements.
two statements.
statements.
If you have two words an OR of the two words is a bitwise OR. If, for example you has
If
If you
If you
you have
have
have two
two words
two words an
words an OR
an OR of
OR of the
of the two
the two words
words isis
two words is aaa bitwise
bitwise OR.
bitwise OR. If,
OR. If, for
If, for example
for example you
example you has
you has
has
two 8-bit words:
two
two 8-bit
two 8-bit words:
8-bit words:
words:
01100010
01100010
01100010
01100010
11110000
11110000
11110000
11110000

you one determines their OR as follows:


you
you one
you one determines
one determines their
determines their OR
their OR as
OR as follows:
as follows:
follows:
01100010
01100010
01100010
01100010
11110000
11110000
11110000
OR 11110000
11110010
OR
OR 11110010
11110010
OR 11110010

That is,
That is, you
you get
get 0,
0, where
where there
there are
are two
two 00 bits,
bits, and
and otherwise
otherwise 1.
1.
That
That is,
is, you
you get
get 0,
0, where
where there
there are
are two
two 00 bits,
bits, and
and otherwise
otherwise 1.
1.

192
192
192
192
192
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO Final
FInalexample
example
JAVA 5: FILES AND JAVA IO FInal example

XOR
XOR
XOR
ItIt
Itisis
isan
anoperation
an operationthat
operation thatbasically
that basicallyworks
basically workson
works ontwo
on twobits,
two bits,and
bits, andwhere
and wherethe
where theresult
the resultisis
result isaaabit
bitwhich
bit whichisis
which is11
1
ififthe
the two
two arguments
arguments are
aredifferent
differentand
and00ififthey
theyare
are equal.
equal.The
Theoperation
operation may
may
if the two arguments are different and 0 if they are equal. The operation may be expressedbe
beexpressed
expressed
inin
inthethefollowing
the followingtable:
following table:
table:

Arg 1 Arg 2 XOR


Arg 1 Arg 2 XOR
0 0 0
0 0 0
0 1 1
0 1 1
1 0 1
1 0 1
1 1 0
1 1 0

The
The operation
Theoperation corresponds
correspondstoto
operationcorresponds the
tothe opposite
oppositeofof
theopposite ofaaabiimplication
biimplication
biimplicationofof two
oftwo statements.
twostatements.
statements.

IfIf you
Ifyou have
youhave two
havetwo words
twowords an
wordsan XOR
XORofof
anXOR the
ofthe two
thetwo words
wordsisis
twowords isaaabitwise
bitwise XOR.
XOR.If,If,
bitwiseXOR. If,forfor example
forexample you
exampleyou
you
has
has two
hastwo 8-bit
two8-bit words:
8-bitwords:
words:

01100010
01100010
11110000
11110000

you
youdetermines their XOR ininthe following manner:
you determines
determines their
their XOR
XOR in the
the following
following manner:
manner:

01100010
01100010
11110000
11110000
XOR 10010010
XOR 10010010

NOT
NOT
NOT
NOT
NOT is acting on aasingle bit by simply turning the bit. The operation can be described
NOT is is acting
acting on
on a single
single bit
bit by
by simply
simply turning
turning the
the bit.
bit. The
The operation
operation can
can be
be described
described
ininaatable
tableasasfollows:
follows:
in a table as follows:

Arg NOT
Arg NOT
0 1
0 1
1 0
1 0

The operation
operationisis
Theoperation similar
similartoto
issimilar toaaamathematical
mathematical negation.
mathematicalnegation.
negation.
The

193
193
193
JAVA 5: FILES AND JAVA IO Final example
FInal
JAVA 5: FILES AND JAVA IO FInal example

If
If you
you have
have aa word
word aa NOT
NOT of
of the
the word
word is
is aa bitwise
bitwise NOT.
NOT. If,
If, for
for example
example you
you have
have an
an
8-bit word:
8-bit word:

01100010
01100010

you
you determines
determines its
its NOT
NOT follows:
follows:

01100010
01100010
NOT
NOT 10011101
10011101

That
That is, that a NOT is the same
same as the
the complement of
of the word.
word.
That is,
is, that
that aa NOT
NOT is
is the
the same as
as the complement
complement of the
the word.

EXAMPLES
EXAMPLES
EXAMPLES
III will
will conclude
conclude this section
will conclude this
section with aa few
this section with
few examples of
with a few examples
of how using
examples of how
using the binary
how using the
binary operations to
the binary operations
to
operations to
manipulate the
manipulate the individual bits
bits in aa word.
word. Remember in in this context
context that the
the smallest unit
unit
manipulate the individual
individual bits in
in a word. Remember
Remember in this
this context that
that the smallest
smallest unit
that
that directly can be addressed on aa computer is aa byte, and you can not directly address
that directly
directly can
can be
be addressed
addressed on
on a computer
computer is
is a byte,
byte, and
and you
you can
can not
not directly
directly address
address
the
the individual
individual bits.
bits.
the individual bits.

Given
Given a 16-bit word:
word:
Given aa 16-bit
16-bit word:

0011101111100001
0011101111100001

BUSINESS HAPPENS HERE.


www.fuqua.duke.edu/globalmba

194
194
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO FInal
FInal example
example

Usually
Usually are the bit positions numbered from behind starting with 0, and so that the last
Usually are
Usually are the
are the bit
the bit positions
bit positions numbered
positions numbered from
numbered from behind
from behind starting
behind starting with
starting with 0,
with 0, and
0, and so
and so that
so that the
that the last
the last
last
bit
bit has index 0, while the first bit has index 15. In this case I would like to set the bit
bit has index 0, while the first bit has index 15. In this case I would like to set the bit
bit has
has index
index 0,
0, while
while the
the first
first bit
bit has
has index
index 15.
15. In
In this
this case
case I
I would
would like
like to
to set
set the
the bit
bit
number
number
number 33
3 to
to
to 1
1
1

no
no
no matter
matter
matter what
what
what value
value
value it
it
it may
may
may already
already
already have.
have.
have. This
This
This can
can
can be
be
be done
done
done with
with
with the
the
the
number 3 to 1 no matter what value it may already have. This can be done with the
following
following
following expression:
expression:
following expression:
expression:

0011101111100001
0011101111100001 OR
0011101111100001 0000000000001000
OR 0000000000001000
OR 0000000000001000

If
If in a certain position you OR a 00 to the first bit pattern the result in that position will
If in
If in aaa certain
in certain position
certain position you
position you OR
you OR aaa 0
OR 0 to
to the
to the first
the first bit
first bit pattern
bit pattern the
pattern the result
the result in
result in that
in that position
that position will
position will
will
be
be unchanged and be the same as the value of the first bit pattern to OR a 0 do not
be unchanged and be the same as the value of the first bit pattern to OR a 0 do not
be unchanged
unchanged and
and be
be the
the same
same as
as the
the value
value of
of the
the first
first bit
bit pattern
pattern
to
to OR
OR a
a 0
0 do
do not
not
change
change
change anything.
anything. If
If in
in aa certain
certain position
position you
you OR
OR aa 11 to
to the
the first
first bit
bit pattern
pattern the
the result
result in
in
change anything. If in a certain position you OR a 1 to the first bit pattern the result in
anything. If in a certain position you OR a 1 to the first bit pattern the result in
that
that
that position
position
position will
will
will certainly
certainly
certainly be
be
be 1
1
1 regardless
regardless
regardless of
of
of the
the
the value
value
value of
of
of the
the
the first
first
first bit
bit
bit pattern
pattern
pattern may
may
may have
have
have
that position will certainly be 1 regardless of the value of the first bit pattern may have
had.
had. The result of the foregoing is, therefore,
had. The
The result
result of
of the
the foregoing
foregoing is,is, therefore,
therefore,

0011101111100001
0011101111100001 OR
0011101111100001 OR 0000000000001000 =
OR 0000000000001000 0011101111101001
0000000000001000 =
= 0011101111101001
0011101111101001

The
The example can immediately be generalized to other word lengths and thus shows how to
The example
The example can
example can immediately
can immediately be
immediately be generalized
be generalized to
generalized to other
to other word
other word lengths
word lengths and
lengths and thus
and thus shows
thus shows how
shows how to
how to
to
set
set
set a
a
a particular
particular
particular bit
bit
bit of
of
of 1.
1.
1.
set a particular bit of 1.

A
A related task concerns how to set a particular bit to 0, no matter what value itit may have.
A related
A related task
related task concerns
task concerns how
concerns how to
how to set
to set aaa particular
set particular bit
particular bit to
bit to 0,
to 0, no
0, no matter
no matter what
matter what value
what value it
value it may
may have.
may have.
have.

Given
Given a 16-bit word:
Given aaa 16-bit
Given 16-bit word:
16-bit word:
word:

0011101111100001
0011101111100001
0011101111100001

the
the
the set
set bit
bit 88 to
to 0:
0:
the set
set bit
bit 88 to
to 0:
0:

0011101111100001
0011101111100001 AND
0011101111100001 1111111011111111
AND 1111111011111111
AND 1111111011111111

If
If you in a certain position AND a 11 to the first bit pattern the result in that position will
If you
If you in
you in aaa certain
in certain position
certain position AND
position AND aaa 1
AND 1 to
to the
to the first
the first bit
first bit pattern
bit pattern the
pattern the result
the result in
result in that
in that position
that position will
position will
will
be
be
be the
the
the same
same
same as
as
as the
the
the value
value
value of
of
of the
the
the first
first
first bit
bit
bit pattern
pattern
pattern
that
that
that AND
AND
AND aa
a 1
1
1 does
does
does not
not
not change
change
change anything.
anything.
anything.
be the same as the value of the first bit pattern that AND a 1 does not change anything.
If
If you
you in
in a certain position AND a 00 to the first bit pattern the result in that position
If
If you in aaa certain
you in certain position
certain position AND
AND aaa 0
position AND to
0 to the
to the first
the first bit
first bit pattern
bit pattern the
pattern the result
the result
result inin that
in that position
that position
position
certainly
certainly
certainly will
will be
be 00
0 regardless
regardless of
of the
the value
value of
of the
the first
first bit
bit pattern
pattern may
may have
have had.
had. The
The result
result
certainly will be 0 regardless of the value of the first bit pattern may have had. The result
will be regardless of the value of the first bit pattern may have had. The result
of
of
of the
the foregoing
foregoing is,
is, therefore,
therefore,
of the
the foregoing
foregoing is, is, therefore,
therefore,

0011101111100001
0011101111100001 AND
0011101111100001 AND 1111111011111111 =
AND 1111111011111111 0011101011100001
1111111011111111 =
= 0011101011100001
0011101011100001

The
The example can immediately be generalized to other word lengths and thus show how to
The example
The example can
example can immediately
can immediately be
immediately be generalized
be generalized to
generalized to other
to other word
other word lengths
word lengths and
lengths and thus
and thus show
thus show how
show how to
how to
to
set
set
set a
a
a particular
particular
particular bit
bit
bit to
to
to 0.
0.
0.
set a particular bit to 0.

195
195
195
195
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example
JAVA 5: FILES AND JAVA IO FInal example

As
As aa final
final example
example II want
want to
to show
show how
how to
to test
test ifif aa particular
particular bit
bit is
is 00 or
or 1.
1. Given
Given aa 16-bit
16-bit
word:
word:

0011101111100001
0011101111100001

So,
So, II would
would like
like to
to test
test the
the value
value of
of bit
bit 4.
4. Consider
Consider the
the following
following expression:
expression:

(0011101111100001
(0011101111100001 SHIFT
SHIFT RIGHT
RIGHT 4)
4) AND
AND 0000000000000001
0000000000000001

If the
If the value
value of
of this
this expression
expression is
is 0,
0, then
then the
the bit
bit 44 is
is also
also 0.
0. Otherwise,
Otherwise, bit
bit 44 is
is 1.
1. You
You could
could
also also
also also test
test bit
bit 44 more
more directly
directly by
by looking
looking at
at the
the value
value of
of the
the following
following expression:
expression:

0011101111100001 AND
0011101111100001 AND 0000000000010000
0000000000010000

ENCODING OF
ENCODING OF CHARACTERS
CHARACTERS
Above II have
Above have shown
shown how
how to
to represent
represent integers
integers on
on aa computer
computer that
that works
works exclusively
exclusively binary
binary
that is
that is where
where all
all data
data are
are represented
represented as
as sequences
sequences ofof 00 and
and 11 bits.
bits. II have
have also
also demonstrated
demonstrated
how the
how the computer
computer by by the
the use
use of
of complement
complement arithmetic
arithmetic can
can perform
perform thethe four
four arithmetical
arithmetical
operations. A
operations. A computer
computer works
works with
with other
other data
data types
types than
than integers
integers and
and such
such aa computer
computer
must be
must be able
able to
to work
work with
with text.
text. In
In this
this section
section II will
will show
show how
how to to represent
represent text
text using
using
binary numbers.
binary numbers.

There are
There are several
several ways,
ways, but
but the
the principle
principle is
is simple,
simple, as
as you
you for
for each
each letter,
letter, digit
digit and
and other
other
characters associates
characters associates aa numeric
numeric code,
code, and
and the
the only
only thing
thing that
that is
is necessary
necessary isis to
to agree
agree on
on an
an
encoding table
encoding table that
that for
for each
each character
character determines
determines which
which code
code to
to be
be used.
used. That
That isis where
where the
the
differences occurs,
differences occurs, as
as historically
historically are
are used
used multiple
multiple tables.
tables.

ASCII
ASCII
Ill start
Ill start with
with aa table
table called
called ASCII
ASCII (American
(American Standard
Standard Code
Code for
for Information
Information Interchange)
Interchange)
that may
that may not
not be
be used
used directly
directly with
with modern
modern computers,
computers, but
but it
it is
is yet
yet an
an important
important table
table to
to
know. The
know. The table
table encodes
encodes characters
characters as
as 11 byte
byte numeric
numeric codes,
codes, and
and the
the table
table then
then has
has room
room
for 256
for 256 characters.
characters. The
The table
table is
is usually
usually divided
divided into
into three
three parts
parts

1.
1. the codes
1. the codes 031
031 that
that defines
defines various
various control
control characters
characters
2.
2. the codes
2. the codes 32127
32127 that
that defines
defines standard
standard characters
characters from
from the
the english
english alphabet
alphabet
3.
3. the codes
3. the codes 128255
128255 that
that defines
defines among
among other
other country-specific
country-specific characters
characters

Note that
Note that the
the first
first two
two parts
parts totally
totally consists
consists of
of 128
128 codes,
codes, and
and thus
thus can
can be
be represented
represented by
by
77 bits,
bits, and
and the
the first
first ASCII
ASCII tables
tables (the
(the first
first standard)
standard) covered
covered only
only the
the first
first two
two parts
parts and
and
was thus
was thus aa 7-bit
7-bit encoding.
encoding.

196
196
196
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example

Below
Below isis the
the first
first part
part of
of the table where
the table where II partly
partly have
have shown
shown codes
codes (both
(both in
in decimal,
decimal,
binary
binary and
and hexadecimal)
hexadecimal) and
and partly symbolic characters
partly symbolic characters name
name and
and aa brief
brief descriptive
descriptive text.
text.
Note
Note that
that these
these codes
codes do
do not
not directly correspond to
directly correspond to the
the characters
characters on
on the
the keyboard
keyboard but
but are
are
control
control codes,
codes, many
many ofof which
which are defined for
are defined for the
the purpose
purpose ofof data
data communication
communication in in which
which
text
text has
has to
to be
be transmitted
transmitted over one or
over one or another
another communication
communication line.line.

DEC BIN HEX Symbol Text

0 00000000 00 NUL Null char

1 00000001 01 SOH Start of heading

2 00000010 02 STX Start of text

3 00000011 03 ETX End of text

4 00000100 04 EOT End of transmission

5 00000101 05 ENQ Enquiry

6 00000110 06 ACK Acknowledgment

7 00000111 07 BEL Bell

Excellent Economics and Business programmes at:

The perfect start


of a successful,
international career.

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

197
197
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example

DEC BIN HEX Symbol Text

8 00001000 08 BS Back space

9 00001001 09 HT Horizontal tab

10 00001010 0A LF Line feed

11 00001011 0B VT Vertical tab

12 00001100 0C FF Form feed

13 00001101 0D CR Carrige return

14 00001110 0E SO Shift out / X-on

15 00001111 0F SI Shift In / X-off

16 00010000 10 DLE Data link escape

17 00010001 11 DC1 Device control 1 (oft. XON)

18 00010010 12 DC2 Device control 2

19 00010011 13 DC3 Device control 3 (oft. XOFF)

20 00010100 14 DC4 Device control 4

21 00010101 15 NAK Negative acknowledgement

22 00010110 16 SYN Synchronous idle

23 00010111 17 ETB End of transmitblock

24 00011000 18 CAN Cancel

25 00011001 19 EM End of medium

26 00011010 1A SUB Substitute

27 00011011 1B ESC Escape

28 00011100 1C FS File separator

29 00011101 1D GS Group separator

30 00011110 1E RS Record separator

31 00011111 1F US Unit separator

198
198
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example

Below
Below II have
have listed
listed the
the codes
codes used
used with
with plain text:
plain text:

--- LF,
LF, used
used for
for line
line break
break
--- HT,
HT, used for the tabulator
used for the tabulator character
character
--- FF, used for page break
FF, used for page break
--- ESC,
ESC, the
the ESC
ESC keykey
--- BS,
BS, the backspace key
the backspace key

Below
Below isis the
the second
second part
part of
of the
the table,
table, which defines codes
which defines codes for
for characters
characters in
in the
the English
English
alphabet:
alphabet:

DEC BIN HEX DEC BIN HEX DEC BIN HEX

32 00100000 20 64 01000000 40 @ 96 01100000 60

33 00100001 21 ! 65 01000001 41 A 97 01100001 61 a

34 00100010 22 66 01000010 42 B 98 01100010 62 b

35 00100011 23 # 67 01000011 43 C 99 01100011 63 c

36 00100100 24 $ 68 01000100 44 D 100 01100100 64 d

37 00100101 25 % 69 01000101 45 E 101 01100101 65 e

38 00100110 26 & 70 01000110 46 F 102 01100110 66 f

39 00100111 27 71 01000111 47 G 103 01100111 67 g

40 00101000 28 ( 72 01001000 48 H 104 01101000 68 h

41 00101001 29 ) 73 01001001 49 I 105 01101001 69 i

42 00101010 2A * 74 01001010 4A J 106 01101010 6A j

43 00101011 2B + 75 01001011 4B K 107 01101011 6B k

44 00101100 2C , 76 01001100 4C L 108 01101100 6C l

45 00101101 2D - 77 01001101 4D M 109 01101101 6D m

46 00101110 2E . 78 01001110 4E N 110 01101110 6E n

47 00101111 2F / 79 01001111 4F O 111 01101111 6F o

48 00110000 30 0 80 01010000 50 P 112 01110000 70 p

49 00110001 31 1 81 01010001 51 Q 113 01110001 71 q

50 00110010 32 2 82 01010010 52 R 114 01110010 72 r

51 00110011 33 3 83 01010011 53 S 115 01110011 73 s

52 00110100 34 4 84 01010100 54 T 116 01110100 74 t

53 00110101 35 5 85 01010101 55 U 117 01110101 75 u

54 00110110 36 6 86 01010110 56 V 118 01110110 76 v

55 00110111 37 7 87 01010111 57 W 119 01110111 77 w

199
199
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example

DEC BIN HEX DEC BIN HEX DEC BIN HEX

56 00111000 38 8 88 01011000 58 X 120 01111000 78 x

57 00111001 39 9 89 01011001 59 Y 121 01111001 79 y

58 00111010 3A : 90 01011010 5A Z 122 01111010 7A z

59 00111011 3B ; 91 01011011 5B [ 123 01111011 7B {

60 00111100 3C < 92 01011100 5C \ 124 01111100 7C |

61 00111101 3D = 93 01011101 5D ] 125 01111101 7D }

62 00111110 3E > 94 01011110 5E ^ 126 01111110 7E ~

63 00111111 3F ? 95 01011111 5F _ 127 01111111 7F

Note particularly
Note particularly the
the code
code 32, which is a space.

This encoding
This encoding isis not
not sufficient,
sufficient, as there are a number of other letters that are
are national.
national. For
For
example the
example the Danish
Danish letters
letters ,
, and , but there are also other characters found
found on
on aa keyboard,
keyboard,
for example
for example ,
, andand may
may also
also include other special characters such as the Greek
Greek alphabet.
alphabet.

200
200
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

Encoding
Encoding of of these
these symbols
symbols have
have been
been solved
solved by
by defining
defining extended
extended ASCII
ASCII tables
tables for
for codes
codes
128255
128255 that
that defines
defines additional
additional 128
128 characters.
characters. AA concrete
concrete machine
machine can
can then
then load
load the
the
table
table extension
extension that
that you
you want
want toto use.
use. As
As an
an example
example isis aa code
code table,
table, called
called ISO
ISO 8859-1,
8859-1,
which
which includes
includes the
the Danish
Danish letters,
letters, and
and below
below isis shown
shown the
the codes
codes of
of the
the Danish
Danish letters
letters in
in
ISO
ISO 8859-1:
8859-1:

--- 230
230
--- 248
248
--- 229
229
--- 198
198
--- 216
216
--- 197
197

Consider
Consider as
as an
an example
example the
the text
text

Hello
Hello World
World

where
where there
there are
are 11
11 characters.
characters. IfIf this
this text
text isis encoded
encoded asas ASCII
ASCII and
and stored
stored in
in the
the machines
machines
memory,
memory, itit uses
uses 11
11 bytes
bytes plus
plus one,
one, andand the
the contents
contents of
of the
the memory
memory might
might be:
be:

where
where the
the content
content isis shown
shown in in hexadecimal
hexadecimal (so (so its
its easier
easier for
for us
us humans
humans to to read),
read), and and where
where
the
the arrow
arrow indicates
indicates the
the address
address where
where thethe text
text isis stored.
stored. Note
Note the
the first
first byte
byte that
that indicates
indicates
how
how long
long the
the text
text is.
is. In
In one
one wayway or
or another
another there
there must
must bebe stored
stored information
information about about where
where
the
the text
text ends,
ends, and
and itit does
does not
not have
have to
to bebe aa counter,
counter, as as shown
shown above,
above, but
but itit isis one
one ofof the
the
ways
ways used.
used. Note
Note also
also that
that ifif you
you as
as illustrated
illustrated above
above uses
uses one
one byte
byte to
to specify
specify the the length,
length,
then
then aa text
text has
has aa maximum
maximum length length of
of 255
255 characters.
characters. The The problem
problem cancan ofof course
course easily
easily be
be
overcomed
overcomed by by using
using twotwo bytes
bytes to to or
or more
more to to indicate
indicate thethe length.
length.

ItIt isis important


important to
to note
note that
that there
there nowhere
nowhere areare said
said something
something about
about that
that the
the 12
12 bytes
bytes should
should
be
be interpreted
interpreted asas text,
text, and
and how
how those
those bytes
bytes are
are processed
processed isis completely
completely determined
determined of of the
the
program
program that that reads
reads the
the 12
12 bytes.
bytes. As
As an
an example
example couldcould aa program
program choose
choose toto interpret
interpret the
the
12
12 bytesbytes as
as three
three 32-bit
32-bit integers,
integers, and
and the
the program
program willwill then
then read
read the
the following
following numbers:
numbers:

0B48656C = 189293932
6C6F2057 = 1819222103
6F726C64 = 1869769828

201
201
JAVA 5: FILES AND JAVA IO Final example

which is something completely different than the text Hello World. A program can in
principle read arbitrary bytes and interpret them as it will, but if it makes sense is a whole
different matter.

UNICODE

The encoding used today, is called Unicode, and the purpose is to replace the many different
code pages known from ASCII, with a single code page, which contains all possible characters
in all different languages. The price for it is obviously a very large table (just think of all
non-European languages, chemical symbols, mathematical symbols, etc.), and it is also the
systems disadvantage, both because it can be difficult to define a table, which all agree on, or
that it could be expensive to use such a large table, if you really only need a small subset.

There is defined two different systems:

-- UTF (Unicode Transfer Format)


-- USC (Universal Character Set)

and each of these systems has multiple encodings, and I will mention the following:

-- UTF-8, which is an 8-bit variable length encoding, which basically is a kind of


extension of the ASCII system, and in particular is widely used on the Internet
-- UTF-16 which is a 16 bit variable length encoding used by Windows
-- UTF-32, which is a 32-bit fixed-length encoding, is used to some extent in the
Unix and Linux (the same as the UCS-4)

Mention must also UCS-2, which is a fixed-length 16-bit encoding, that only has support
a subset of all Unicodes.

That an encoding is of fixed length means that all characters take up the same. In UTF-32
all the characters so fills 4 bytes. Is an encoding of variable length, the characters does not
fill the same, and basically it is the principle that characters used often has codes with a
smaller size, while characters used rarely take up more space. It is a choice. Fixed length
encoding is the simplest but pay by space consumption, while a variable length encoding
minimizing the required to space, and pay with a more complex encoding, which places
extra demands on the software.

202
JAVA
JAVA 5:
5: FILES
FILES AND
AND JAVA
JAVA IO
IO Final
FInal example
example

UTF-16
UTF-16
Ill
Ill start
start with
with UTF-16
UTF-16 as as the
the encoding
encoding used
used under
under Windows
Windows andand also
also Linux.
Linux. All
All codes
codes are
are
2
2 or
or 44 bytes.
bytes. The
The first
first 256
256 ASCII
ASCII codes,
codes, that
that fully
fully correspond
correspond to
to ISO
ISO 8859-1,
8859-1, uses
uses two
two
bytes
bytes (16
(16 bits)
bits) for
for each
each character.
character. As
As an
an example
example is
is the
the encoding
encoding of
of aa large
large A
A

0041

For all of the most frequently occurring characters 16 bits are used and they have thus hex
codes from 0000 to FFFF, which gives 65,536 different codes. All other codes occupies 4
bytes or 32 bits. All the 16 bits codes is called Basic Multilingual Plane (BMP).

UTF-16 is an ISO standard that has the name ISO / IEC 10646 and include most of the
worlds characters. In principle, the 4 bytes to assign codes corresponds to to 4,294,967,296
characters, but not all are used, and the encoding of 4 bytes code is relatively complex.
Below is a general description.

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

enroll by September 30th, 2014 and


save up to 16% on the tuition!
pay in 10 installments / 2 years
Interactive Online education
visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

203
203
JAVA 5: FILES AND JAVA IO Final example
JAVA 5: FILES AND JAVA IO FInal example

For codes outside the BMP defines UTF-16 character codes in the range 10000 10FFFF
For codes outside the BMP defines UTF-16 character codes in the range 10000 10FFFF
that gives 1048576 codes. Each code is translated into two codes, called a surrogate pair.
that gives 1048576 codes. Each code is translated into two codes, called a surrogate pair.
The procedure is as follows:
The procedure is as follows:

1. if the code, which according to the standard belongs to the interval [10,000;
1. if the code, which according to the standard belongs to the interval [10,000;
10FFFF] subtracts 10000 from the code, and the result is certainly less than or
10FFFF] subtracts 10000 from the code, and the result is certainly less than or
equal to FFFFF, and thus fills a maximum of 20 bits
equal to FFFFF, and thus fills a maximum of 20 bits
2. split the 20-bit code into 2 halves of 10 bits
2. split the 20-bit code into 2 halves of 10 bits
3. adds D800 to the left half (as max is 3FF) that gives a value in the range [D800; DBFF]
3. adds D800 to the left half (as max is 3FF) that gives a value in the range [D800; DBFF]
4. adds DC00 to the right half (as max is 3FF) that gives a value in the range
4. adds DC00 to the right half (as max is 3FF) that gives a value in the range
[DC00; DFFF]
[DC00; DFFF]

It provides precise 1024 * 1024 = 1048576 pairs (10 bits provides 1024 different values).
It provides precise 1024 * 1024 = 1048576 pairs (10 bits provides 1024 different values).

The standard guarantees that there will never be defined surrogate pairs outside these ranges.
The standard guarantees that there will never be defined surrogate pairs outside these ranges.
Note that the two intervals are disjoint, and the reason for the somewhat complex encoding
Note that the two intervals are disjoint, and the reason for the somewhat complex encoding
is that it must be simple to decode four bytes unicodes.
is that it must be simple to decode four bytes unicodes.

UTF-8
UTF-8
UTF-8 is an encoding that is used much on the Internet as it directly is an expansion of
UTF-8 is an encoding that is used much on the Internet as it directly is an expansion of
ASCII coding, and as it strives to be sent as few bits as possible. It is a variable-length
ASCII coding, and as it strives to be sent as few bits as possible. It is a variable-length
encoding,
encoding, using
using from
from 11 to
to 66 bytes
bytes per character. In
per character. In practice,
practice, however,
however, aa maximum
maximum of
of 44
bytes,
bytes, as
as itit is
is sufficient
sufficient to
to encode
encode the
the entire UTF-16 area.
entire UTF-16 area.

The
The table
table below
below shows
shows the
the principles
principles for encoding the
for encoding the UTF-16
UTF-16 area,
area, where
where aa bb indicates
indicates
aa data
data bit:
bit:

Unicode UTF-8 Number of characters

000000 00007F 0bbbbbbb 128

000080 0007FF 110bbbbb 10bbbbbb 1920

000800 00FFFF 1110bbbb 10bbbbbb 10bbbbbb 63488

010000 1FFFFF 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb 2031616

204
204
JAVA 5: FILES AND JAVA IO Final example

UTF-32

This encoding uses 32 bits for all the characters, and that means that text encoded by this
standard takes up more memory. The system is used only to a limited extent in the Unix
world. In principle, many text operations are simpler when all characters take up the same,
but in practice the gains are modest.

REPRESENTATION OF DECIMAL NUMBERS


Above I have shown how to represent integers in a computer where positive integers are
directly represented as binary numbers, and negative integers are represented by their 2
complement. A computer must also be able to work with decimal fractions, and it is
once more difficult. There are a number of ways, but basically they can be divided into
two categories

1. decimal numbers with fixed decimal point, which in many ways is an extension of
the representation of integers, so that there is a number of the bits for the integer
part and a number of bits for the fractional part
2. decimal numbers with floating point, where you have a certain number of bits for
the whole number, but the bits used for the integer part and which are used for
the fractional part depends on the numbers current value

The two categories are quite different, and the first is by far the simplest, but is best suited
The numbers
if the two categories
do notarespread
quite different,
over tooand
widethean
first is by far
interval. The thesecond
simplest, but is best
category suiteda far
enables if the
numbers
greater do not
range spread overbut
of numbers, toothe
wide an interval. The
representation is second category enables a far greater range of
more complex.
numbers, but the representation is more complex.
I will only look at the last category. Partly because it is the most used form of representation
I will only look at the last category. Partly because it is the most used form of representation of the
of the decimal numbers, and partly because thats where most are to add in terms of what I
decimal numbers, and partly because that's where most are to add in terms of what I have previously
have previously shown. One speaks generally about floating-point numbers, and here again
shown. One speaks generally about floating-point numbers, and here again there are several variants,
there
but are several
I would lookvariants, but called
at a standard I would look
IEEE at a standard
Standard called
754, which IEEE
is the mostStandard
commonly754,
usedwhich
standard
is the most commonly
for representing used standard
floating-point numbers. for representing floating-point numbers.

A BIT MORE ABOUT BINARY NUMBERS

In A
thebit more about
introduction binary
I mentioned numbers
that an integer in the 10-number system can be represented
as a sum
In the introduction I mentioned that an integer in the 10-number system can be represented as a sum

10
=0

where the symbols 0, 1, . . . , are digits in the decimal number system, and I also mentioned how
this representation can be generalized to an arbitrary base and especially to the base 2 and the binary
number system. Looking again at the 10-number system, the notation can be used to describe arbitrary
decimal numbers, that is numbers which include fractions:


205

10
In
In the
the introduction
introduction III mentioned
mentioned that
that an
an integer
integer in
in the
the 10-number
10-number system
system can
can be
be represented
represented as
as aaa sum
sum
In the introduction mentioned that an integer in the 10-number system can be represented as sum


JAVA 5: FILES AND JAVA IO Final example

10
10
10
=0
=0
=0
where the symbols a0, a1,an are digits in the decimal number system, and I also mentioned
where
where
how
where
the
this
the symbols
symbols
symbols 0,
therepresentation 1, ......,, are
0,
0, 1,. can
1, . . , be are digits
digits in
generalized
are digits in the
in the decimal
decimal
to decimal
the
number
number
an arbitrary
number
system,
system,
base
and
and III also
and and
system, also mentioned
especially
also mentioned
to the base
mentioned
how
how
how2
this representation
this representation
representation can
can be be generalized
be generalized
generalized to an
to an arbitrary
an arbitrary
arbitrary base
base and
and especially to the
especially system,
to the base
the base
base 2 and the binary
this
and the can
binary number system. to
Looking again atbase
theand especially
10-number to the22 notation
and the
and the binary
binary
can
number
number system.
system. Looking
Looking again
again at at the
atdecimal10-number
the 10-number
10-number system,
system, the
the notation
notation can
can be used
be used
used to describe
to describe
describe arbitrary
arbitrary
number
be used system. Looking
to describe again
arbitrary the numbers, system,
thattheis notation
numbers can be
which to
include arbitrary
fractions:
decimal
decimal numbers,
numbers, that
that is numbers
numbers which
which include
include fractions:
decimal numbers, that isis numbers which include fractions:
fractions:




10
10
10
=
=
=

IfIf you
you looks
you
IfIf you looksat
looks
looks atatthe
at the
the
number
the
number
number
1234.56,
number
1234.56,
1234.56,
itit can
1234.56, can be
it can it
be
written
becan be as
written
written written as
as
as
3
33


10
10
10
=2
=2
=2

where
where
where
where 2
=
= 6,
2 =
2 6,
6, 1
=
= 5,
1 =
1 5,
5,
=
= 4,
000 = 4,
4,
=
= 3,
111 = 3,
3,
=
= 2,
222 = 2,
2,
=
=1
333 =
.
11..

This
This notation
notation in
in which
which you
you works
works with
with negative
negative powers
powers of
of the
the basic
basic number,
number, may
may also
also be
be used
used for
for
This notation in which you works with negative powers of the basic number, may also be used for
binary
binary numbers.
numbers. Consider
Consider the
the binary
binary number
number
binary numbers. Consider the binary number

10110.10010111
10110.10010111
10110.10010111

which
which this this time
time has
has aaa fraction.
fraction. It is easy
easy to
to determine
determine the
the number's
number's value
value as
as aaa decimal
decimal number,
number, because
which this time has fraction. ItIt isis easy to determine the number's value as decimal number, because
because
itit still just
still just is a sum
just isis aa sum of
sum of powers
of powers of
powers ofof 2:2:
2:
it still
4 2 1 4 6 7 8
10110.10010111
10110.10010111222 =
=2 +
+2 +
+2 +
+2 1 + 24
+ 224 +
+2 627 +
+2 8 = 22.58984375
10110.10010111 = 2244 + 2222 + 22 + 221 + + 226 227 + 228 = 22.58984375
= 22.58984375

However,
However, you
you should
should note
note that
that if the
the result
result is calculated
calculated on
on aaa machine,
machine, the
the result
result will
will be
be rounded,
rounded, if
However, you should note that ifif the result isis calculated on machine, the result will be rounded, ifif

140
140
140

206
33
3

10
10
=2
=2
=2
JAVA
JAVA
JAVA 5:
5: FILES
5: FILES AND
FILES AND JAVA
AND JAVA IO
JAVA IO Final
FInal
IO FInal example
example
example


where = 6, = 5, = 4,
4, = 3,
3, = 2,
2, = 11..
where 2 = 6,
2
2 1 = 5,
1
1 000 = 111 = 222 = 333 =
This
This notation
notation inin which
which you
you works
works with
with negative
negative powers
powers of of the
the basic
basic number,
number, may
may also
also be
be
This
used
This notation
for
notation in
binary
in which
which you
numbers.
you works with
Consider
works with negative
the binary
negative powers of
number
powers
used for binary numbers. Consider the binary number of the
the basic
basic number,
number, may
may also
also be
be used
used for
for
binary numbers.
binary numbers. Consider
Consider the
the binary
binary number
number
10110.10010111
10110.10010111
10110.10010111
10110.10010111
which this time has a fraction. It is easy to determine the numbers value as a decimal
which thistimetime
which this
which this time hashas has a fraction.
aa fraction.
fraction. It is
It
It to
is easy
easy is determine
easy to determine
to determine number'sthe
the number's
the
numbers
value
value
valuenumber,
as aa decimal
as decimal as a decimal
because
number, because
number,
number, because
because it
it still
still just
just is
is a
a sum
sum of
of powers
powers of
of 2:
2:
itit still
still just
just is
is aa sum
sum of
of powers
powers of
of 2:
2:

10110.10010111 = 22444 +
10110.1001011122 = + 22222 +
+ 22 + 1
+ 221
1 + 4
+ 224 6
+ 226
4 + 62 7
27 8
+ 228
7 + = 22.58984375
8 = 22.58984375
2

However, you
However, you should
should note
note that
that if
if the
the result
result is
is calculated
calculated on
on aa machine,
machine, the
the result
result will
will be
be rounded,
rounded, if
if
However, you
However, you should
should note
note that
that ifif the
the result
result is
is calculated
calculated on
on aa machine,
machine, the
the result
result will
will be
be
rounded,
rounded,
there ifif bits
are many
many there
there
bits arethe
are
after many
many bitspoint,
bits
decimal afterfor
after theexample
the decimal point,
decimal point, for
for example
example
there are after the decimal point, for example
140
140
13 14
1.0000000000001122 =
1.00000000000011 = 11 +
+ 2213 + 2214
13 + = 1.0001831054688
14 = 1.0001831054688
2

You can
You can also
also convert
convert the
the decimal
decimal number
number to
to aa binary
binary fraction.
fraction. This
This is
is done
done by
by converting
converting the
the integer
integer
You
You
part andcan
can also
thealso convert
convert
fractional the
partthe decimal number
decimalConsider
separately. numberthe
Consider to a binary
thetonumber
a binary
number fraction. This is done by converting
fraction. This is done by converting
123.45
part and the fractional part separately. 123.45
the integer
the integer part
part and
and the
the fractional
fractional part
part separately.
separately. Consider
Consider the
the number
number 123.45
123.45
The integer
The integer part
part can
can be
be converted
converted as
as shown
shown previously:
previously:
The integer
The integer part
part can
can be
be converted
converted as
as shown
shown previously:
previously:
123 =
123 =
64 +
64123
+ 5959 ==
123 =
=
64 +
64 + 3232 ++ 27 =
27 =
64
64+ +
+3259
59+ =
=16 +
64
6464+ +3232+ 16 + 11 =
11 =
+
+1627 =
6464+
64 + +32
3232+
+ 27+
16 +
=
8 +
8 + 3 3 =
=
64
64 +
+ 32
32+ +
+1616
16+ +
+ 11
112 ==+
64 + 32
6464+ +3232+ 1616+ 8
8 +
+ 2+ +3 1
1
64 + 32 +
+ 16 +
+ 88 + 3 =
=
64
64 ++ 3232 +
+ 16
16 +
+ 88 + + 2
2 +
+ 1
1
or by
or by division
division by
by 2.
2. The
The result
result is
is that 123 =
that 123 = 1111011
1111011
The
or byfraction
divisionpart
by can be converted
2. The by 123
result is that multiplying by 2:
= 1111011
or fraction
The
The
by division
fraction bybe
part can
part can 2.converted
be The result
converted by is
by
that 123by
multiplying
multiplying by=2:
2: 1111011

The -multiply
- multiply
fraction part the
can fraction bypart by 2
The fraction
multiply part
the can be
the fraction
fraction converted
part
bepart 22
converted
by
by
by multiplying
multiplying by by 2:2:
- - the integer part, that is 0 or 1, is the next bit
thethe integer
integer part,
part, that
that is
is 00 or
or 1,
1, is
is the
the next
next bit
bit
-
repeat - repeat
-- multiply
repeat above
above until
until until the
the fraction
fraction fraction
partbyis 0,part is have
0, orthe
you havenumber
the wantedbitsnumber of bits
above
multiply the fraction
the the
fraction part
partpart byis 20, or
2 or you
you have the wanted
wanted number of bits
of
-- the
the integer
integer part,
part, that
that isis 0 0 or
or 1, 1, is
is the
the next
next bit
bit
This
This
This means
means
means that you
that finds the
you finds next
the bit of
next multiplying
bit of by two,
multiplying and
bythen
two,continue withcontinue
and then the fractional
withpart
the
repeat above until the fraction part is 0, or and
that
-- repeat you finds
above the
untilnextthebit of multiplying
fraction part by
is two,
0, or youthen
you havecontinue
have the with
the wanted
wanted the fractional
number
number of part
of bits
bits
to this result.
tofractional
this result. part to this result.
This means that you
youis:finds
finds the
the next
next bit
bit of
of multiplying
multiplying by
by two,
two, and
and then
then continue
continue with
with the
InThis
In this
means
this case,
case, thethat
the method
method is:
the
fractional
fractional part
part to
to this
this result.
result.
45
45
0 90
0 90
1 80
1 80
1 60
1 60
1 20
1 20
0 40
0 40
0 80
0 80
1 60
1 60
207
207
....
.... 207
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO Final
FInalexample
example
JAVA 5: FILES AND JAVA IO FInal example

InInthis
thiscase,
case,the
themethod
methodis:is:
In this case, the method is:
45
45
0 90
0 90
1 80
1 80
1 60
1 60
1 20
1 20
0 40
0 40
0 80
0 80
1 60
1 60
....
....

and the result is that 1111011.0111001 = 123.45 which is a rounded result.


and the result is that 1111011.0111001 = 123.45 which is a rounded result.

Asanother
As another example,thethe considerthe
the decimalnumber
number 0.0825.Here,
Here, it is onlynecessary
necessary to
As anotherexample,
example, theconsider
consider thedecimal
decimal number0.0825.
0.0825. Here,ititisisonly
only necessarytoto
convertthe
convert the fractionalpart,
part, as theinteger
integer partisis0:0:
convert thefractional
fractional part,asasthe
the integerpart
part is 0:

0825
0825
0825
00 1650
1650
0 1650
00 3300
03300
3300
00 6600
6600
0 6600
11 3200
13200
3200
00 6400
6400
0 6400
11 2800
12800
2800
00 5600
5600
0 5600
11 1200
11200
1200
00 2400
2400
0 2400
00 4800
04800
4800
00 9600
9600
0 9600
11 9200
19200
9200
11 8400
8400
1 8400
11 6800
16800
6800
11 3600
3600
1 3600

The result: 0.0825 = 000101010001111


The result: 0.0825 = 000101010001111

Notethat
Note that if I convertsthe
the binaryresult
result to a decimalnumber,
number, I get0.0824890137
0.0824890137 so you
Note thatififI Iconverts
converts thebinary
binary resulttotoaadecimal
decimal number,I Iget
get 0.0824890137sosoyou
you
cansee
can seethat
thatthere
theremust
mustbebemany
manybits
bitstotoget
getan
anaccurate
accurateresult.
result.
can see that there must be many bits to get an accurate result.

208
208
208
JAVA 5: FILES AND JAVA IO Final example

FLOITING POINT

The decimal numbers are a subset of the real numbers, and the problem is to represent real
numbers using a finite number of bits, for example 32 or 64 which is the most common.
In general, a real number is represented in the form

where the s field always fills 1 bit and represents the sign, the exponent field is an exponent
and the significand field is used for numbers digits.

209
JAVA
JAVA5:5:FILES
FILESAND
ANDJAVA
JAVAIO
IO Final
FInalexample
example

The
Themain
mainproblem
problemisisthat
thatthe
therepresentation
representationofofaareal realnumber
numberisisnot
notunique,
unique,butbutisisalways
alwaysaa
rounded
roundedresult.
result.AArepresentation
representationofofthe
theintegers
integersdefines
definesaasubset
subsetofofthe
theintegers,
integers,such
suchthat
thatall
all
integers
integersininaarange
rangeisisrepresented.
represented.Similarly
Similarlyititis,is,by
bythe
therepresentation
representationofofthethereal
realnumbers,
numbers,
that
that since there are only a limited number of bits available, wee can represent onlyaasubset
since there are only a limited number of bits available, wee can represent only subset
ofofthe
thereal
realnumbers,
numbers,and andthus
thusthe
thereal
realnumbers
numberswithin withinaarange,
range,but
butunlike
unlikethetheintegers
integers
includes
includesanyanyinterval
intervalofofreal
realnumbers
numbersinfinite
infinitemanymanynumbers,
numbers,andandanyanyrepresentation
representationofof
real
realnumbers
numbersby byusing
usingaaspecific
specificnumber
numberofofbitsbitscan canonly
onlyrepresent
representaasubset
subsetofofthe
therange.
range.
Another problem is that a decimal number such as 123.45 can not be converted
Another problem is that a decimal number such as 123.45 can not be converted to a binary to a binary
number
numberwith withaafinite
finitenumber
numberofofbits:
bits:

123.45 = 1111011.011100110011001100110011

So there is no clear relation between decimal fractions and the binary numbers.
So there is no clear relation between decimal fractions and the binary numbers.
32 BITS FLOITING POINTS
32 BITS FLOITING POINTS
Ill start with a representation that takes up 4 bytes, i.e. 32 bits:
Ill start with a representation that takes up 4 bytes, i.e. 32 bits:
- 1 bit to the sign
--- 18bit
bitstofor
thethesign
eksponent
-- 81 bit
bitsto for
the sign
the eksponent
-18bit
23tobits for
thethe the significand
signeksponent
-- 23bits for
bits for the significand
823 bitsbits
forforthe eksponent
1 bit to the the signsignificand
The sign 23 bits
bit for
is 0 the
if significand
the number is non-negative and 1 if the number is negative. If you look
The 18bit
sign
bit
bitsto for
is
thethe
0 if
sign eksponent
the number is non-negative and 1 if the number is negative. If you look
at
Thethe
sign 8significand
bit
bits
23 is for
for
bits 0the field
ifthe it contains
thesignificand
number
eksponent the 23 bits:
is non-negative and 1 if the number is negative. If you look at the
at
Thethe
sign significand
significand23bit is for
field
bits 0 itifthefield it contains
thesignificand
containsnumber the 23 bits:
is bits:
the 23 non-negative and 1 if the number is negative. If you look at the
significand field it contains the 23 bits:
bbbbbbbbbbbbbbbbbbbbbbbb
The sign bit is 0 if the number is non-negative and 1 if the number is negative. If you look at the
bbbbbbbbbbbbbbbbbbbbbbbb
The sign bit fieldis 0 itif contains
bbbbbbbbbbbbbbbbbbbbbbbb
significand the number is bits:
the 23 non-negative and 1 if the number is negative. If you look at the
bbbbbbbbbbbbbbbbbbbbbbbb
significand field it contains the 23 bits:
and it is interpreted as the binary number
and
and itit is
is interpreted
interpretedas as
bbbbbbbbbbbbbbbbbbbbbbbb thethe
binary number
binary number
and it is interpreted
bbbbbbbbbbbbbbbbbbbbbbbb as the binary number
127
1.
and it is interpreted as the binary number 2
1.
and it is interpreted as the binary number 2127
where n is the value of the exponent field. 127 is called the bias value,
1. which is binary 01111111. It is
2127
the
wheren n
where is is the
the value value
of the ofexponent
the exponentfield. 127 field.
is called 127the is bias called value, bias value,
which is which is binary
used ton ensure
where is the that the content
value of 1.
the of the exponent
exponent field. field 127 is not is negative.
called the 127
2 I would
bias as binary
value,
01111111.
an example
which look
is
It the
at
binary
is
01111111.
used It
to ensure that
number is used to
the content ensure
of the exponent that the content
isfield of
is notbitnegative. the exponent field
I would binary is not
as an example negative.
look atistheI
where n 123.45.
01111111. is the
It is
Since
value ofitthe
used
is aexponent
to
positive
ensure
number
field.the
that 127 thecalled
is
content
sign
ofthethe 0.bias Thevalue,number's
exponent which representation
is binary
field is not01111111.
negative. ItIis
number
wouldn 123.45.
where as the
is Sinceofitthe
an value
example islook
aexponent
positive
at thenumber number
field. 127 is is the123.45.sign bit
called the 0.bias
Since Thevalue, itnumber's
is awhich binary
positiveis representation
number
binary is theisItsign
01111111. is
used
would to
as ensure
an that
example the content
look at ofthe the exponent
number field
123.45. is not
Since negative. it is aI would
positive as an example
number is look
the at
sign the
bit
used 0.
number The
to 123.45
ensure numbers
123.45. that
=Since itbinary
the content ofrepresentation
the exponent
number isfield
1.1110110111001100110011001100110011001100110011.
is a positive is sign
the is notbitnegative. 0. The number's I would binary
as an example . look
. 26atisthe
representation
bit 0. The
123.45 numbers
= binary representation
1.1110110111001100110011001100110011001100110011. is
number 123.45. Since it is a positive number is the sign bit 0. The number's binary representation . . 26 is
Therefore,
123.45the =content of the significand field is 11101101110011001100110 (the . first
1.1110110111001100110011001100110011001100110011. . 261 digit
Therefore,
before123.45the content of the significand field is 11101101110011001100110
= 1.1110110111001100110011001100110011001100110011.
the decimal (the
point is implicit). Since 133-127 = 6 is the content of the exponent field . . 2is61133
first digitor
before
binary the decimal point
10000101. Then is implicit). Since 133-127 = 6 is the content of the exponent field is 133 or
Therefore, the content of the
thenumber 123.45
significand is represented
field as the bit pattern
is 11101101110011001100110 (the first 1 digit
binary 10000101.
Therefore, the Then
content of the
thenumber 123.45
significand is represented
field is as the bit pattern
11101101110011001100110 (the firstis1133
digitor
before the decimal point is implicit). Since 133-127 = 6 is the content of the exponent field
before the decimal point
Thenisthe
implicit).
01000010111101101110011001100110
binary 10000101. numberSince 133-127
123.45 = 6 is the
is represented content
as the of the exponent field is 133 or
bit pattern
01000010111101101110011001100110
binary 10000101. Then the number 123.45 is represented as the bit pattern
In the case of floiting point are not used complement arithmetic, and a negative number is handled
01000010111101101110011001100110
In the
only bycase of floiting
changing pointbit.
the sign
01000010111101101110011001100110 areAsnot
an used complement
example is -123.45arithmetic, and as
is represented a negative number is handled
only by changing the sign bit. As an example is -123.45 is represented as
In the case of floiting point are not used complement 210
210 arithmetic, and a negative number is handled
In11000010111101101110011001100110
the by
only case of floiting
changing pointbit.
the sign areAsnot
an used complement
example is -123.45arithmetic, and as
is represented a negative number is handled
where nn is
where is the
the value
value of
of the
the exponent
exponent field.
field. 127
127 is
is called
called the bias value,
the bias value, which
which is
is binary
binary 01111111.
01111111. ItIt is
is
where n is the value of the exponent field. 127 is called the bias value, which is binary 01111111. It is
used to
used to ensure
ensure that
that the
the content
content ofof the
the exponent
exponent field
field is
is not
not negative.
negative. II would
would as
as an
an example
example look
look at
at the
the
used to ensure that the content of the exponent field is not negative. I would as an example look at the
number 123.45.
number 123.45. Since
Since itit is
is aa positive
positive number
number isis the
the sign
sign bit
bit 0.
0. The
The number's
number's binary
binary representation
representation is
is
number
JAVA 5: 123.45. Since
FILES AND JAVAit isIOa positive number is the sign bit 0. The number's binary representation is
Final example
JAVA 5: FILES AND JAVA
JAVA IO FInal example
JAVA 5: FILES
FILES AND JAVA IO FInal example
123.45 =
123.45 = 1.1110110111001100110011001100110011001100110011.
1.1110110111001100110011001100110011001100110011. .. . . 226666
123.45 = 1.1110110111001100110011001100110011001100110011. . . 2
Therefore,
Therefore,thethe content
thecontent
content of
of the
the significand
significand field is
is 11101101110011001100110 (the
(the 11first 1
Therefore,
Therefore, the content of the
of the significand
significand field field
field 11101101110011001100110
is 11101101110011001100110
is 11101101110011001100110 (the first
(the first first
digit1
digit
Therefore,
digit the content of the significand field is 11101101110011001100110 (the first 1 digit
digit before
before
before before the
the decimal
the decimal decimal point
point is
is implicit).
point is implicit).
implicit).implicit). Since
Since= 133-127
Since 133-127 133-127
6 is the =
=66 is
the content the
thethecontent
is of content of the
the exponent
of field
exponent exponent
is 133 or or
before the
the decimal
decimal point
point is
is implicit). Since
Since 133-127
133-127 = = 66 is
is the content
content ofof the
the exponent
exponent field
field isis 133
133 or
field
binary is 133 or
10000101. binary
Then 10000101
the number . Then
123.45 the
is number
represented 123.45
as the is
bit represented
pattern
field is 133 or binary 10000101. Then the number 123.45 is represented as the bit pattern as the bit pattern
binary 10000101. Then the number 123.45 is represented as the bit pattern
binary 10000101. Then the number 123.45 is represented as the bit pattern
01000010111101101110011001100110
01000010111101101110011001100110
01000010111101101110011001100110
01000010111101101110011001100110
01000010111101101110011001100110

Inthe
In
In thecase
the caseofof
case offloiting
floiting
floiting
floiting point
point
point are
areare not
notnot used
usedused complement
complement arithmetic,
arithmetic,
complement and a negative
and aa negative
arithmetic, negative
and number
number number
is handledis
handledis
In
Inthe
In thecase
the caseof
case ofoffloiting
floitingpoint
point
point
are not
areare
used
notnot
complement
usedused
arithmetic,
complement
complement
and
arithmetic,
arithmetic, and aa negative
and a negative
number
negative is
number number
is handledis
only
only by changing
handled
by
handledchanging
only bythe
only thechanging
sign bit.
sign bit. As
As ansign
thean example is
bit. is
example -123.45
As-123.45 is represented
represented
an example
is as is represented
is -123.45
as represented as
only only by
by changing
handled bythechanging the
theansign
sign bit. As
changing bit.
bit. isAs
example
sign an
an example
As-123.45 is
is -123.45
is represented
example as is
-123.45 is represented as
as
11000010111101101110011001100110
11000010111101101110011001100110
11000010111101101110011001100110
11000010111101101110011001100110
11000010111101101110011001100110
that is
that is the same
same bit
bit pattern
pattern as
as 123.45
123.45 except
except the
the sign
sign bit.
bit.
that isthe
that the same bit pattern as 123.45 except the sign bit.
bit.
thatisis
that isthethe
same
the bit pattern
same
same bit as 123.45
bit pattern
pattern as except the
as 123.45
123.45 sign bit.
except
except the
the sign
sign bit.

AN EXAMPLE
AN EXAMPLE
An example
AN EXAMPLE
An example
To highlight the
the principle II will
will look atat a small calculation.
calculation. Suppose aa floating
floating point contains
contains
To
To highlight
highlight the principle
principle I will look
look at aa small
small calculation. Suppose
Suppose a floating point
point contains
To
thehighlight
To thebits:
following principle II will
bits: will look
look at
at aa small
small calculation.
calculation. Suppose
Suppose aa floating
floating point
point contains
contains the
the
thehighlight
the
To highlight
the
following principle
thebits:
following principle I will look at a small calculation. Suppose a floating point contains the
following bits:
following bits:
following bits:
11000111001100111100111001010100
11000111001100111100111001010100
11000111001100111100111001010100
11000111001100111100111001010100
11000111001100111100111001010100
When the
When the first
first bit
bit is
is 1,
1, it
it represents
represents aa negative
negative number.
number. The
The exponent
exponent part
part is
is 10001110
10001110,,
Whenthe
When
When thethe first
first bit1,
bit is
is 1,isit
it 1, it represents
represents a negative
a negative
negative number. number. Thepart
The exponent
exponent exponent
part part is which
10001110,
is 10001110, 10001110
which the,
is the
When
which is first
whichtheis the bit
first
the number
bit is
number 1, it
represents
and aasubtract
142, and
represents
142, subtract
negative
number.
the bias The
number.
the bias The
you gets 15. part is
you exponent
gets 15. is 10001110, which
is
is the
which 142,
number
number is theandnumber
subtract142, andyou
the bias subtract
gets 15.the bias you gets 15.
number 142,
142, andand subtract
subtract thethe bias
bias you
you gets
gets 15.
15.
Thesignificand
The significand
significand part
part is 01100111100111001010100
is and
andand
the number
the is then
then
The
The
Thesignificand
The significand
significand
part
part
partpart is 01100111100111001010100
is 01100111100111001010100
is 01100111100111001010100
is and
01100111100111001010100
01100111100111001010100 the the number
the number
the number
andand
is then is
is
is then
number
number then is then
15
1.01100111100111001010100 215
1.01100111100111001010100 = 1011001111001110.01010100 =
= 46030.3213
1.01100111100111001010100 215 =
215 = 1011001111001110.01010100
1011001111001110.01010100 = 46030.3213
46030.3213

and the value


and value of the
the number is
is -46030.32813.
and the
the value of
of the number
number is -46030.32813.
143
-46030.32813.
143
143
There is little
There little variation in
in terms ofof how the
the boundary conditions
conditions are treated,
treated, but basically
basically
There is
is little variation
variation in terms
terms of how
how the boundary
boundary conditions are are treated, but
but basically
can be assumed
can assumed as follows.
follows. The exponent
exponent field represents
represents values inin the range
range of 00 to 255,
255,
can be
be assumed as as follows. The
The exponent field
field represents values
values in the
the range of
of 0 to
to 255,
but 255 which
but which has thethe value 11111111
11111111 that is is illegal. The
The power of
of 2 exponent
exponent thus lies
lies
but 255
255 which has has the value
value 11111111 that that is illegal.
illegal. The power
power of 22 exponent thus
thus lies
between -127 and
between and 127. TheThe largest positive
positive number is: is:
between -127
-127 and 127.127. The largest
largest positive number
number is:

01111111011111111111111111111111
01111111011111111111111111111111

211
211
211
211
and the little
There value of the number is -46030.32813.
There isis little variation
variation in
in terms
terms of of how
how the
the boundary
boundary conditions
conditions areare treated,
treated, but
but basically
basically can
can be
be
assumed
assumed as follows. The exponent field represents values in the range of 0 to 255, but 255 which has
There is
There isas little
follows.
little The exponent
variation
variation termsfield
in terms
in
represents
of how
of how values inconditions
the boundary
the boundary the range are
conditions
of 0treated,
to 255, but
arebetween
but basically
treated, -127
255 whichcan
but basically
hasbe
can be
the value
theassumed 11111111
value 11111111 that
that is illegal.
isexponent
illegal. TheThe power
power of 2 exponent
of 2 values
exponent thus lies
thusrange
lies of
between -127 and
and 127.
127. The
The
assumed as follows.
as follows. The
The field represents in the 0 to 255,
exponent field represents values in the range of 0 to 255, butFinal but 255 which has
255 which has
largest
JAVA
largest positive
JAVA 5: FILES
FILES AND
positive
5: number
JAVA
number
AND JAVAis:
is:IO
IO FInal example
example
the value
the value 11111111
11111111 that
that is illegal.
is illegal. The
The power
power of
of 22 exponent
exponent thus
thus lies
lies between
between -127
-127 and
and 127.
127. The
The
largest positive number
largest positive number is: is:
01111111011111111111111111111111
01111111011111111111111111111111
The exponent is 11111110 127 =
The exponent is 11111110 127 = 254-127254-127 = = 127,
127, and
and the
the greatest
greatest positive
positive number
number is
is
therefore
01111111011111111111111111111111
01111111011111111111111111111111
therefore
The exponent is 11111110 - 127 = 254-127 = 127, and the greatest positive number is therefore
The exponent is 11111110 - 127 = 254-127 = 127, and the greatest positive number is therefore
The exponent
The exponent is
is 11111110
11111110 -- 127
127 =
= 254-127
254-127 =
=127
127, and
127, and the
the greatest
greatest positive
positive number
number is
is therefore
therefore
104
1.11111111111111111111111
1.11111111111111111111111 2 2 127 =
= 111111111111111111111111
111111111111111111111111 2
2 104
38
=
= 3.402823466
3.402823466 10 38
10 2127
127 104
1.11111111111111111111111
1.11111111111111111111111 2 = 111111111111111111111111
= 111111111111111111111111 2
2104
38
= 3.402823466
= 3.402823466 10
1038
Similarly,
Similarly, the smallest
the smallest positive number:
positive number:
Similarly,
Similarly, the
the smallest
smallest positive
positive number:
number:
Similarly, the smallest positive number:
Similarly, the smallest positive number:
00000000000000000000000000000001
00000000000000000000000000000001
00000000000000000000000000000001
00000000000000000000000000000001
00000000000000000000000000000001
The exponent is 00000000 - 127 = -127 and the number is
The exponent is 00000000 - 127 = -127 and the number is
The exponent
The exponent is is 00000000
00000000 127
127 = = -127
-127 and
and the
the number
number is
is
The exponent
The exponent is
is 00000000
00000000 -- 127
127 =
= -127
-127 and
and127
the number
the number is
is 150
1.00000000000000000000001
1.00000000000000000000001 2 2127 = = 100000000000000000000001
100000000000000000000001 2
2150
39
=
= 5.87747245
5.87747245 10
10 39 127 150
1.00000000000000000000001 2
1.00000000000000000000001 2127 == 100000000000000000000001
100000000000000000000001 2
2150
39
= 5.87747245 1039
= 5.87747245 10
(it
(it is
is one
one of
of the
the numbers
numbers that
that vary
vary slightly).
slightly). The
The result
result is
is that
that you
you can
can assume
assume that
that the
the standard
standard may
may
represents
represents numbers within the following range:
(it is
(it onenumbers
is one of the
of
within the
the numbers
numbers thatfollowing
that
range: The result is that you can assume that the standard may
vary slightly).
vary slightly). The result is that you can assume that the standard may
represents numbers
represents numbers within
within the
the following
following
38
range:
range:
38 38 38
[10 1038]]
[1038;; 10 [10 1038]]
[1038;; 10
38
[1038 38 ] 38
[1038 38 ]
24 [10 ;; 10
1038 ] [10 ;; 10
1038 ]
and
and that when2
that when 224 =
= 16777216
16777216,, there
there are
are about
about 77 significant
significant digits.
digits.
24
and that
and that when
when2 224 = 16777216
= 16777216,, there
there are
are about
about 77 significant
significant digits.
digits.
Individual
Individual bit
bit patterns
patterns are
are assigned
assigned aa special
special meaning:
meaning:
Individual bit
Individual bit patterns
patterns are
are assigned
assigned aa special
special meaning:
meaning:
Bit
Bit pattern
pattern Value
Value
00000000000000000000000000000000
00000000000000000000000000000000 0
0 Value
Bit pattern
Bit pattern Value
01111111100000000000000000000000
01111111100000000000000000000000 Infinity
Infinity
00000000000000000000000000000000
00000000000000000000000000000000 00 inifinity
Join the best at
11111111100000000000000000000000
11111111100000000000000000000000
01111111100000000000000000000000
01111111100000000000000000000000
Minus
Minus
Infinity
Infinity
Top masters programmes
inifinity
33rd place Financial Times worldwide ranking: MSc
01111111110000000000000000000000 Not aa number
the Maastricht University
01111111110000000000000000000000
11111111100000000000000000000000
11111111100000000000000000000000
Not
Minus
number
Minus inifinity
inifinity
International Business
1st place: MSc International Business
Not aa number
number
but School of Business and
01111111110000000000000000000000
01111111110000000000000000000000
but there
there are
are others.
others.
Not 1st place: MSc Financial Economics
2nd place: MSc Management of Learning

but Economics!
but there
there are others.
are others.
2nd place: MSc Economics
2nd place: MSc Econometrics and Operations Research
2nd place: MSc Global Supply Chain Management and
Change
64
64 bits
bits floiting
floiting points
points Sources: Keuzegids Master ranking 2013; Elsevier Beste Studies ranking 2012;
Financial Times Global Masters in Management ranking 2012

64 bits
64 bits floiting
floiting points
points
The
The principle
principle is
is the
the same
same as
as above,
above, but
but using
using 64
64 bits
bits which
which are
are interpreted
interpreted as
as follows:
follows:
Maastricht
The principle
The principle is
is the
the same
same as
as above,
above, but
but using
using 64
64 bits
bits which
which are
are interpreted
interpreted as
as follows:
follows: University is
11 bit
bit to
to the
the sign
sign the best specialist
university in the
Visitbitus
11 bit to and
to find out why we are the best!
the sign
the sign Netherlands
(Elsevier)
144
Masters Open Day: 22 February
1442014
144
144
www.mastersopenday.nl

212
212
The
The exponent
exponent isis 00000000
00000000 -- 127
127 == -127
-127 and
and the
the number
number isis
The exponent is 00000000 - 127 = -127 and the number is
The exponent is 00000000 - 127 = -127 and the number is
JAVA 5:
1.00000000000000000000001 2127
1.00000000000000000000001 2127 127 = 100000000000000000000001 2150
= 100000000000000000000001 150
2example
5: FILES
FILES AND
AND JAVA
JAVA IO
JAVA1.00000000000000000000001
IO 39 Final
FInal 150
example
JAVA1.00000000000000000000001
=
5: FILES AND JAVA
JAVA 5: FILES AND JAVA 5.87747245
IO
= 5.87747245
IO
10 22127
1039
= 100000000000000000000001
= 100000000000000000000001

FInal
2
2 150
example
FInal example
39
= 5.87747245
= 5.87747245 10 1039
(it
(it
(it
isis one
oneofof
of the
the numbers
numbers that
that vary
vary slightly).
slightly). The
Theisisresult
result isis can
that you
you can
thatassumecan assume
assume that the
thatmay
the
(it isisisone
(it one
oneofofthe numbers
thethe
numbers that
numbersthat vary
vary slightly).
that slightly).
vary The
The result
result
slightly). The that
that you
result you
is can
thatassume
you that the
the standard
thatassume
can standard
that may
the
(it is one may
(it is
standard
standard oneofof
may therepresents
thenumbers that
numbers
represents vary slightly).
that
numbers
numbers vary
within
within The
the result
slightly). The is thatrange:
following
theresult result
following you can assume that the standard may
is
range: that you can assume that the
represents
(it is
representsone numbers
of the
numbers within
numbers
within the
that
the following
vary
following range:
slightly). The
range: is that you can assume that the standard may
standard
represents may
standard numbers represents numbers
within the followingwithin
range:the following range:
represents may numbers represents
within thenumbers
following within
range:the following range:
[1038
[10 38; 103838] [1038
38 ; 1038 ]] [10
38; 1038 38]
38 ; 1038 ]]
[10 ; 10 [10
[1038 ; 1038 ] [1038 ; 1038 ] ; 10
and
and that
and
and thatwhen
that
that when2224
when
when 242=
242=
24 16777216
24
=16777216 ,, there
= 16777216,
16777216, there are
there
there about
areare
are 77 significant
about
about
about digits.
77 significant
significant digits. digits.
significant digits.
and
and that
that
and that
when
when2242=24 16777216, there are about 7 significant digits.
= 16777216,
2 2= 16777216 there are about 7 significant digits.
and thatwhen
when 24
= 16777216,, there are are
there about 7 significant
about digits. digits.
7 significant
Individual
Individual bit
bit patterns are assigned aa special meaning:
Individual
Individual bitpatterns
bit
Individual bit patternsare are
patterns
patterns
assigned
are are assigned
assigned
assigned
special
a special
meaning:
aa special
special meaning:
meaning:
meaning:
Individual
Individual bit
bit patterns
patterns are are assigned
assigned a a
special special meaning:
meaning:
Individual bit patterns are assigned a special meaning:
Bit pattern
Bit pattern Value
Value
Bit
Bit pattern
pattern Value
pattern Value Value
Bit
Bit pattern
00000000000000000000000000000000
pattern Value
Value
00000000000000000000000000000000 0Value
0
Bit pattern
00000000000000000000000000000000 0
00000000000000000000000000000000
01111111100000000000000000000000
01111111100000000000000000000000 0Infinity
Infinity
01111111100000000000000000000000
00000000000000000000000000000000 Infinity
0
01111111100000000000000000000000
11111111100000000000000000000000
00000000000000000000000000000000
11111111100000000000000000000000 Infinity
Minus
Minus inifinity
0 inifinity
00000000000000000000000000000000
01111111100000000000000000000000
11111111100000000000000000000000 0Infinity
Minus inifinity
11111111100000000000000000000000
01111111100000000000000000000000
01111111110000000000000000000000
01111111110000000000000000000000 Minus
Not a
Infinity
Not a inifinity
number
number
01111111100000000000000000000000
11111111100000000000000000000000
01111111110000000000000000000000 Infinity
Minus inifinity
Not a number
11111111100000000000000000000000
01111111110000000000000000000000 Minus
Not a inifinity
number
11111111100000000000000000000000
01111111110000000000000000000000 Minus
Not a inifinity
number
01111111110000000000000000000000
but
but there
there are
are others.
others. Not a number
01111111110000000000000000000000 Not a number
but there are others.
but there are others.
but there are others.
but
but there
there are
are others.
others.
but there are others.
64 bits
64BITS floiting
bitsFLOITING points
floitingPOINTS
points
64
64
64
64
bits
64BITS
bits
BITS
floiting points
floitingPOINTS
FLOITING
FLOITING points
POINTS
64 BITS FLOITING POINTS
The
The principle
The principle
principle isthethe
is the samesame
as as above,
as above, but but 64
but using using
bits 64 bitsare
which which are interpreted
interpreted as follows: as
as follows: follows:
The
The
The principleis
The principle
principle
principle isis
isthethe
is the
same
the same
same
same
above,
as
as above,
above,
as above,
same as
using
but
but using
above, but
64 bits64
but using
using
64
using
which
64
bits 64 bitsare
bits
which
bits
interpreted
which
which
are are
are interpreted
interpreted
which are as follows: as
interpreted
interpreted as follows:
as follows:
follows:
The principle is the same as above, but using 64 bits which are interpreted as follows:
- 111 bit to
to the
bitbit to sign
the signsign
the
--- 111bit
bit
bitto to
the
to signsign
the
the sign
-- 11 bit
11bitto the
bits sign
to for
thethe
signeksponent
--- 11
11 bits
bits for
for the
the eksponent
eksponent
-- 11
52 bits
bits for
for the
the eksponent
significand 144
--- 52
52 bits
bits for
for the
the significand
significand 144
- 52 bits for the significand 144
144
The bias value is 1023, that binary is 01111111111.
The bias value is 1023, that binary is 01111111111.
The bias value is 1023, that binary is 01111111111.

Consider as an example the number 12345.6789. Binary it is


Consider as
Consider
Consider as an
as an example
an example the
example the number
the number 12345.6789.
number 12345.6789. Binary
12345.6789. Binary itit
Binary it isis
is
11000000111001.1010110111001100011000111111000101000001.....
11000000111001.1010110111001100011000111111000101000001.....
11000000111001.1010110111001100011000111111000101000001.....

or
or
or
or
1.1000000111001101011011100110001100011111100010100001.....*213
1.1000000111001101011011100110001100011111100010100001.....*213
1.1000000111001101011011100110001100011111100010100001.....*213

Since 13 = 1036 1023 and 1036 = 10000001100 is the representation of 12345.6789:


Since 13
Since 13 == 1036
1036 1023
1023 and
and 1036
1036 == 10000001100
10000001100 is
is the
the representation
representation of
of 12345.6789:
12345.6789:
Since 13 = 1036 1023 and 1036 = 10000001100 is the representation of 12345.6789:
0100000011001000000111001101011011100110001100011111100010100001
0100000011001000000111001101011011100110001100011111100010100001
0100000011001000000111001101011011100110001100011111100010100001
0100000011001000000111001101011011100110001100011111100010100001

213
213
213
213
1.1000000111001101011011100110001100011111100010100001.....*2 13
1.1000000111001101011011100110001100011111100010100001.....*2 13
1.1000000111001101011011100110001100011111100010100001.....*2 13
Since
Since13
13==1036
1036--1023
1023and
and1036
1036==10000001100
10000001100isisthe
therepresentation
representationof
of12345.6789:
12345.6789:
JAVA 5:
5:FILES AND JAVA IO Final example
JAVA
Since FILES
13 = AND
1036JAVA IO and
- 1023 FInal example
1036 = 10000001100 is the representation of 12345.6789:
0100000011001000000111001101011011100110001100011111100010100001
0100000011001000000111001101011011100110001100011111100010100001
JAVA 5: FILES AND JAVA IO FInal example
0100000011001000000111001101011011100110001100011111100010100001
Slightly rounded it provides the opportunity to represent numbers within the following range:
Slightly
Slightlyrounded
rounded it provides
providesthe
theopportunity
opportunity to represent
to represent numbers
numbers withinwithin the following
the following range: range:
Slightly rounded it provides the opportunity to represent numbers within the following range:
Slightly rounded it provides the opportunity to represent numbers within the following range:
Slightly rounded it provides the opportunity
308 to represent numbers
308 308 within
308 the following range:
[10 10308]][10
[10308;; 10 10308]]
[10308;; 10
[10308 ; 10308 ] [10308 ; 10308 ]
and
and it it means
means
andititmeans
and approximately
approximately
means approximately 15 significant
15
approximately 1515 digits.
significant
significant digits.
digits.
significant digits.
andititmeans
and means approximately
approximately 1515
significant digits.
significant digits.
ANOTHER
ANOTHEREXAMPLE
EXAMPLE
Another example
Another example
As aafinal
finalcalculation.
ANOTHER
As EXAMPLE
calculation.Assume
Assumethat
thataareal
realnumber
numberisisrepresented
representedas
asthe
thefollowing
following64-bit
64-bitpattern
pattern
Another example
AsAs
a afinal
As afinal calculation.
calculation.Assume
finalcalculation. Assumethat
Assume thataaareal
that realnumber
real isisrepresented
number
number isrepresentedas
asthe
represented as following
the the 64-bit
following
following pattern
64-bit
64-bit pattern
pattern
0100000100010111000101101100100111001111110001111010001110011000
As a final calculation. Assume that a real number is represented as the following 64-bit pattern
As a final calculation. Assume that a real number is represented as the following 64-bit pattern
Sign:
0100000100010111000101101100100111001111110001111010001110011000
0100000100010111000101101100100111001111110001111010001110011000
0100000100010111000101101100100111001111110001111010001110011000
Sign:
Sign:
0100000100010111000101101100100111001111110001111010001110011000
0,Sign:
the number is positive
Sign:
0,0,the
thenumber
Sign: numberisispositive
positive
0,0,the
thenumber
number isispositive
positive
Exponent:
Exponent:
0, the number is positive
Exponent:
Exponent:
Exponent: 1023 = 1041 1023 = 18
10000010001
Exponent: 1023 = 1041 1023 = 18
10000010001
10000010001
10000010001 -- 1023
1023 == 1041
1041 -- 1023
1023 == 18
Significand:
10000010001 - 1023 = 1041 - 1023 = 18
Significand:
Significand:
Significand:
Significand:
0111000101101100100111001111110001111010001110011000
Significand:
1.0111000101101100100111001111110001111010001110011000 * 218 =
0111000101101100100111001111110001111010001110011000
0111000101101100100111001111110001111010001110011000
0111000101101100100111001111110001111010001110011000
1011100010110110010.0111001111110001111010001110011000
1.0111000101101100100111001111110001111010001110011000 =* 218 =
0111000101101100100111001111110001111010001110011000
378290.45291
1.0111000101101100100111001111110001111010001110011000
1.0111000101101100100111001111110001111010001110011000=** 22 18 ==
1011100010110110010.0111001111110001111010001110011000
18

1011100010110110010.0111001111110001111010001110011000
1011100010110110010.0111001111110001111010001110011000 == 18
378290.45291
1.0111000101101100100111001111110001111010001110011000 * 2 =
378290.45291
378290.45291
1011100010110110010.0111001111110001111010001110011000 =
378290.45291

145
145
145

214
214

You might also like