Java 5: Files and Java IO

3 downloads 305 Views 5MB Size Report
This book is the fifth in a series of books on software development. The programming language is Java, and the language


POUL KLAUSEN

JAVA 5: FILES AND JAVA IO SOFTWARE DEVELOPMENT

Download free eBooks at bookboon.com 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

Download free eBooks at bookboon.com 3

Deloitte & Touche LLP and affiliated entities.

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

360° thinking

49

.

360° thinking

.

360° thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discoverfree theeBooks truth atatbookboon.com www.deloitte.ca/careers Download

Click on the ad to read more

4

Dis

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

Download free eBooks at bookboon.com 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.

Download free eBooks at bookboon.com 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.

Download free eBooks at bookboon.com 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.

Download free eBooks at bookboon.com 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.

Download free eBooks at bookboon.com 9

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

java.io java.Io

2 JAVA.IO 2 JAVA.IO This Thischapter chaptercovers coversstream’s, stream’s,which whichis isa acollection collectionofofclasses classesthat thatprovides providesthe thebasic basicinput input and output operations in Java. A stream is a sequence of data that can be sent over and output operations in Java. A stream is a sequence of data that can be sent overa a communication communicationchannel channelbetween betweena source a sourceand anda destination. a destination.Both Boththe thesource sourceand anddestination destination may be several things as a program, file, one or another external device such as a may be several things as a program, file, one or another external device such as aprinter, printer,a a network networksocket socketororananarray arrayininthe thecomputer’s computer’smemory. memory.Java Javaprovides providesa large a largenumber numberofofclasses classes available, all of which are intended to encapsulate the many details related to sending available, all of which are intended to encapsulate the many details related to sendingdata data over a stream, and it applies to both a stream of bytes, other primitive types and objects over a stream, and it applies to both a stream of bytes, other primitive types and objectsofof allallkinds. kinds.This Thischapter chaptershows showsthe theuse useofofmany manyofofthe theclasses classesfrom from java.io, java.io,and andthe theclasses classes arearepresented primarily through small test methods in the project FileProgram. presented primarily through small test methods in the project 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 afile filehas 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 arrow) is moved forward where the next file operation starts, and the file pointer (the arrow) is moved forward corresponding correspondingtotothe thenumber numberofofbytes bytesread readororwritten. written.Files Filesarearestored storedononthe themachine’s machine’s disk, and the operating system organizes the files in the form of file system that keeps disk, and the operating system organizes the files in the form of file system that keepstrack track ofofdirectories and files. Each file has a unique name consisting of the name of the directory directories and files. Each file has a unique name consisting of the 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 a number of methods class called File, which represents a file by its name and provides a number of methods available availablethat thatcan canbebeused usedtotomanipulate 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());

Download free eBooks at bookboon.com 10

10

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

}

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 that that 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. In this case it is only and the method of one reason or another can not be performed. 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 note note that that aa File File object object can can 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 is a legal file name. These conditions have first importance when the object is used. or is a legal file name. These conditions have first importance when the object is used. The The first first two two statements statements prints prints the the absolute absolute file file name name and and the the canonical canonical file file name. name. In In most most cases cases itit isis the the same, same, but but 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 of of the the program). program). The The next next three three statements statements prints prints respectively respectively the the file file name, name, the the parent parent and and the the path. path. Here Here isis the the file file name name alone alone the the name name of of 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 in in this this case case the the value value of of the the parameter parameter filename. filename. The The last last three three statements statements tests tests 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. In In this this case case isis tested tested whether whether itit isis aa directory directory or or aa file. file. Finally Finally the the 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");

Download free eBooks at bookboon.com 11 11

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

java.io java.Io

fileInfo("/home/pa/doc/xpq/1234"); fileInfo("."); fileInfo(".."); fileInfo("doc");

}

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

Note especially 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 Note invited the example example and and study study the the result. result. invited to to test test the DRIVE DRIVE INFO INFO

NY026057B

TMP PRODUCTION

4

12/13/2013

The prints The following following method method has has aa File File object object as as aa parameter, parameter, and and the the method method PSTANKIE prints information information 6x4 about that disk partition, that contains the file: about that disk partition, that contains the file:

gl/rv/rv/baf

ACCCTR00

Bookboon Ad Creative

private static void print(File root) { System.out.println("Partition: " + root);

All rights reserved.

© 2013 Accenture.

Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon

Download free eBooks at bookboon.com 12 12

Click on the ad to read more

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

}

java.io java.Io

System.out.println("Free space = System.out.println("Usable space = System.out.println("Total space = System.out.println();

" " "

+ + +

root.getFreeSpace()); root.getUsableSpace()); root.getTotalSpace());

All Allsizes sizesare arespecified specifiedininbytes. bytes.When WhengetFreeSpace() getFreeSpace()and andgetUsableSpace() getUsableSpace()usually usuallydo donot not show the same value, it is because the latter is a better estimate, since it takes into account show the same value, it is because the latter is a better estimate, since it takes into account the theoverhead overheadassociated associatedwith withthe thecurrent currentoperating operatingsystem’s system’sfile filesystem. system.The Themethod 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 formy mymachine machineprints printsinformation informationabout aboutthe theroot rootpartition, partition,the thepartition partitionfor forhome home which andfor foran anexternal externalhard harddrive. drive. and THESIZE SIZEOF OFAAFILE FILEAND ANDFILTERS FILTERS THE

Thefollowing followingmethod methodhas hasasasparameter parameteraafile filename nameand andcreates createsaacorresponding correspondingFile Fileobject. object. The thisobject objectrepresents representsaafile, file,the themethod methodprints printsthe thename nameand andthe thesize sizewhere wherethe thesize sizeisis IfIfthis determinedrecursively recursivelyby bythe themethod methodgetSize(), getSize(),which whichdetermines determinesthe thesize sizeofofthe thefile filetree tree determined havingthe theobject objectfile fileasasaaroot. root.Note Notethat thatsize sizeisisaastatic staticvariable, variable,which whichisisdefined definedatatthe the having startofofthe theprogram. program. start 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"); }

Download free eBooks at bookboon.com 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 identifiedby bythe theparameter parametermeets meetscertain certaincriteria. criteria. The FileFilter object is tranfered to the method getSize() together with the File object The FileFilter object is tranfered to the method getSize() together with the File objectthat that isisrepresented representedby bythe 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,the themethod method listFiles() is called, which returns an array of all files in this directory. The method exists listFiles() is called, which returns an array of all files in this directory. The method existsinin several severaloverloadings overloadingsand andinclude includea amethod methodthat 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 methodisiscalled calledand andthe thefirst first parameter is not a directory, there is nothing else than the static variable size is counted parameter is not a directory, there is nothing else than the static variable size is counted with withthe thefile’s file’ssize size––ififititisisa afile filetotobebeincluded includedaccording accordinga apossibly possiblyfilter. filter. Below Belowisisa atest testmethod methodthat thatdetermines determinesthe thesize sizeofofallallfiles filespartly partlyunder underthe thecurrent currentdirectory directory and partly under the user’s home directory. In both cases, it happens with and without and partly under the user’s home directory. In both cases, it happens with and withouta a filter, filter,where wherethe thefilter 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.

Download free eBooks at bookboon.com 1414

JAVA 5: FILES AND JAVA IO JAVA JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO

java.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() { {

The Wake the only emission we want to leave behind

.QYURGGF'PIKPGU/GFKWOURGGF'PIKPGU6WTDQEJCTIGTU2TQRGNNGTU2TQRWNUKQP2CEMCIGU2TKOG5GTX 6JGFGUKIPQHGEQHTKGPFN[OCTKPGRQYGTCPFRTQRWNUKQPUQNWVKQPUKUETWEKCNHQT/#0&KGUGN6WTDQ 2QYGTEQORGVGPEKGUCTGQHHGTGFYKVJVJGYQTNFoUNCTIGUVGPIKPGRTQITCOOGsJCXKPIQWVRWVUURCPPKPI HTQOVQM9RGTGPIKPG)GVWRHTQPV (KPFQWVOQTGCVYYYOCPFKGUGNVWTDQEQO

Download free eBooks at bookboon.com 15 15 15

Click on the ad to read more

JAVA 5: FILES AND JAVA IO JAVA JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO

} }

java.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 user’s user’s home home directory. Next, is created a directory with this name and including a sub-directory named directory. Next, is created a directory with this name and including a sub-directory 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 is is 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 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 where print the absolute file names of all files in the file tree whose root is directory and the file name contains contains the the search search text text text. text. The The result result could could be be the the following: following: name

Download free eBooks at bookboon.com 16 16 16

JAVA JAVA5:5:FILES FILESAND ANDJAVA JAVAIO IO

java.io java.Io

where wherefor foreach eachfile fileare areshown shownthe thefile filename, name,the thedate datewhen whenthe thefile filewas waslast lastmodified modifiedand and the thefile filesize. size.The Theprogram programmust mustnot notdisplay 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 printan anerror errormessage messageon onthe thescreen. screen.

2.2 2.2 RANDOM RANDOMACCESS ACCESSFILES FILES Above AboveI Idescribed describedthe theclass classFile, File,and andhow howaaFile Fileobject objectcan canbe beused usedtotoget getinformation informationabout about files filesand anddirectories directoriesand andtotomanipulate manipulatethe thefile filesystem. system.InInthe therest restofofthis thischapter, chapter,I Iwill will show showhow howtotooperate operateon onthe theindividual individualfiles filesand andthus thusprimarily primarilyhow howtotowrite writedata datatotofiles files and andread readthe thecontent contentofoffiles. files.I’ll I’llstart startwith withRandomAccessFiles, RandomAccessFiles,which whichare arefiles fileswhere whereyou you can canboth bothread readand andwrite writedata dataand andthus thusfiles filesthat thatprograms programscan canasasuse useasassimple simpledatabases. databases. InInfact, fact,that thatkind kindofoffiles fileshas hasnot notsosomuch muchinterest interesttoday, today,but butthey theyare aregood goodtotoknow, know,and and totoknow knowhow howaaprogram programwrites writestotoand andreads readsfrom fromfiles, files,and andthat thatisiswhy whyI Iwill willstart startwith with random randomaccess accessfiles. files.They Theyare areininJava Javarepresented representedby bythe theclass 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);

Download free eBooks at bookboon.com 1717

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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();

30 FR da EE ys tria

SMS from your computer ...Sync'd with your Android phone & number

l!

Go to

BrowserTexting.com

and start texting from your computer!

...

Download free eBooks at bookboon.com 18

18

BrowserTexting

Click on the ad to read more

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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 { file.seek(8); file.writeInt(t5); } catch (IOException ex) { System.out.println(ex); } try (RandomAccessFile file = new { long sum = file.readInt(); sum += file.readInt(); sum += file.readInt(); sum += file.readInt(); System.out.println((long)t1 + System.out.println(sum); } catch (IOException ex) { System.out.println(ex); } try (RandomAccessFile file = new { 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 { double x1 = file.readDouble(); double x2 = file.readDouble(); System.out.println(x1); System.out.println(x2); }

RandomAccessFile("numbers.dat", "rw"))

RandomAccessFile("numbers.dat", "r"))

t2 + t5 + t4);

RandomAccessFile("numbers.dat", "r"))

RandomAccessFile("numbers.dat", "r"))

Download free eBooks at bookboon.com 19 19

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

} }

java.io 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 numbers are not not so interesting, interesting, but you you should note note how they they are initialized initialized as The The numbers are are not so so interesting, but but you should should note how how they are are initialized as as hexadecimal values consisting of 4 bytes. If you do not know hexadecimal numbers, you hexadecimal 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 read the appendix to this book. can can read read the the appendix appendix to to this this book. book. To be 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 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 case is defined aa variable variable dataFile of of the type type RandomAccessFile. It It is opened in in the try try this 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 with the statement statement block 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 statement creates creates aa file file under under the the current current directory directory with with the the name name numbers.dat, numbers.dat, while while The the last parameter tells how to open the file. Basically, there are two options r and rw (there the last last parameter parameter tells tells how how to to open open the the file. file. Basically, Basically, there there are are two two options options rr and and rw rw (there (there the are actually two other options). Here rw means you can both read and write to the file, are actually actually two two other other options). options). Here Here rw rw means means you you can can both both read read and and write write to to the the file, file, are while r means that you can only read the file. The above statement thus opens the file for while rr means means that that you you can can only only read read the the file. file. The The above above statement statement thus thus opens opens the the file file for for while both reading and writing. If the file does not exist, it is created, but otherwise it is just both reading reading and and writing. writing. If If the the file file does does not not exist, exist, itit isis created, created, but but otherwise otherwise itit isis just just both opened and the file pointer is placed at the beginning of the file, so the next file operation opened and and the the file file pointer pointer isis placed placed at at the the beginning beginning of of the the file, file, so so the the next next file file operation operation opened is carried out from this place. carried out out from from this this place. place. isis carried After the file is opened, the first 4 of the above numbers are written to the file. The class After the the file file isis opened, opened, the the first first 44 of of the the above above numbers numbers are are written written to to the the file. file. The The class class After RandomAccessFile has a method writeInt(), which writes an integer to the file. Exactly what RandomAccessFile has has aa method method writeInt(), writeInt(), which which writes writes an an integer integer to to the the file. file. Exactly Exactly what what RandomAccessFile happens is that the method writes 4 bytes from the location where the file pointer is, and happens isis that that the the method method writes writes 44 bytes bytes from from the the location location where where the the file file pointer pointer is, is, and and happens after the method is performed, the file pointer is moved 4 bytes forward. The result is that after the 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 after the four writeInt() statements writes 16 bytes to the file, which represents the 4 integers. the four four writeInt() writeInt() statements statements writes writes 16 16 bytes bytes to to the the file, file, which which represents represents the the 44 integers. integers. the

Download free eBooks at bookboon.com 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, the the file file isis closed. closed. It It isis important, important, as as the the writeInt() writeInt() statements statements writes writes to to aa memory memory buffer. buffer. The The content content of of this this buffer buffer isis first first written written physical physical to to the file when the buffer is full or the file is closed. Another reason for the file to be closed the file when the buffer is full or the file is closed. Another reason for the 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 and and to to ensure ensure that that the the statement statement isis executed, executed, itit isis placed placed in in aa finally finally block block that that isis performed performed regardless regardless of of whether whether an an 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. performs the 2. performs the wanted 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"))

Brain power

By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to maintenance. 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

Download free eBooks at bookboon.com 21 21

Click on the ad to read more

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 after after 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 file file will will be be closed closed when when the the program exits the try block. The syntax is in most cases preferable, first, it is actually shorter program exits the try block. The syntax is in most cases preferable, first, it is actually shorter and and more more readable, readable, and and secondly secondly you you 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 in in the the file, file, and and the the sum sum of of these these numbers numbers isis determined determined and and printed printed along along with with the the sum sum of of the four numbers that are written in the file. The idea is that you have to see that you get the four numbers that are written in the file. The idea is that you 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 the the 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 to to an an int. int. After After the the method method isis performed, performed, the the file file pointer pointer isis moved moved 44 bytes bytes forward. forward. The The method method interprets interprets therefore therefore not not what what the the 44 bytes bytes contains, contains, and and where where 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 what what they they 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 that the third number is overwritten, and the value is now the value of t5. means that the third number is overwritten, and the value is now the value of t5. After After these statements are executed, the file is opened again for reading, and the sum of these statements are executed, the file is opened again for reading, and the sum of the 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 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 In random position position and and read read or or write write from from that that position. position. random

Download free eBooks at bookboon.com 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 andthe thecode codecreates createsan anarray arraywith withroom roomfor for16 16bytes bytes(that (thatexactly exactlymatches matchesthe thecontents contents ofofthe thefile file––ififyou youexamine examineits itsproperties propertieswith withFiles Filesyou youcan cansee seethat thatitittakes takesup up16 16bytes). bytes). Next, Next,read readthe thefile filewith withthe themethod methodread() read()and andthe thearray arrayasasaaparameter. parameter.This Thismethod methodreads reads aamaximum of 16 bytes in the file (less if there are not 16 bytes after the file pointer). maximum of 16 bytes in the file (less if there are not 16 bytes after the file pointer).The The 16 bytes are used to initialize a string, and the result is: 16 bytes are used to initialize a string, and the result is: ABCDEFGHQRSTMNOP

The Thegoal goalisistotoshow showthat thateven eventhough thoughthe thefile filecontains containsfour fourintegers integerswhich whichtotal totaltakes takesup up16 16 bytes, bytes,ititcan canbe beinterpreted interpretedasasanything, anything,and andititisisthe theprogram programthat thatreads readsthe thefile’s file’scontents contents that determines how the results should be interpreted. It is further illustrated with that determines how the results should be interpreted. It is further illustrated withthe thelast last statements in the test method that reads the contents of the file and interprets it as two statements in the test method that reads the contents of the file and interprets 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 about historic people and save the information by object serialization. I information about historic people and save the information by object serialization. Iwill will show a different version of the program where the difference is that the persons instead are show a different version of the program where the difference is that the persons instead are stored storedininaaRandomAccessFile. RandomAccessFile.Let Letme mesay sayimmediately immediatelythat thatthis thissolution solutionhas hasno noadvantages, 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 shownthe theget getand andset setmethods): methods): public class Person implements Comparable, 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

Download free eBooks at bookboon.com 2323

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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 extendedwith withananintintvariable variablenamed namedrecnr. recnr.There Therearearealso alsodefined definedboth bothgetgetand andsetset methods methodsforforthat thatvariable, variable,and andthat thatshould shouldcontain containa person’s a person’slocation locationininthethefile. file.Finally Finallyis is added anan extra constructor. The class is is defined Serializable, and as as Person objects nono longer added extra constructor. The class defined Serializable, and Person objects longer should shouldbebeserialized, serialized,it itcould couldbebedeleted. deleted.

> Apply now redefine your future

- © Photononstop

AxA globAl grAduAte progrAm 2015

axa_ad_grad_prog_170x115.indd 1

19/12/13 16:36

Download free eBooks at bookboon.com 24 24

Click on the ad to read more

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 of of the the type type Person, Person, but but 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 of of these these values. values. As As 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 in in aa database, database, so so in in fact fact the the limitation limitation is is quite quite usual. usual. The The following following class class defines defines aa file file (a (a database) database) to to Person Person objects objects or or 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(); }

Download free eBooks at bookboon.com 25 25

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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);

Download free eBooks at bookboon.com 26 26

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

}

}

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(); }

LIGS University based in Hawaii, USA is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:

▶▶ enroll by October 31st, 2014 and ▶▶ save up to 11% 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.

Download free eBooks at bookboon.com 27 27

Click on the ad to read more

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.

Download free eBooks at bookboon.com 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 as as aa parameter, parameter, the the Person Person object object to to be be added added to to the the file. file. The The method method starts starts by by allocating allocating the the object’s object’s record record number number as as the the next next record record in in the the file, file, and and then then set set the the file file pointer pointer to to the the end end of of the the file. file. The The object object isis then then written written to to the the file file with with the the method method write(). write(). Here Here you you must must notice notice 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 to to the the maximum maximum width. width. The The method method update() update() works works in in principle principle in in the the same same way, way, only only isis used used the the Person Person object’s object’s 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, and and 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 of of the the program program has has aa class class called called Persons, Persons, and and itit isis rewritten rewritten as as shown shown below, below, because because the the program program instead instead of of store store Person Person objects objects by by serilalization serilalization uses uses an an object object of of type type PersonDB. PersonDB. The The class class isis expanded expanded with with aa new new instance instance variable variable called called path, path, which which isis initialized initialized by by the the constructor constructor and and contains contains the the file file name, name, but but otherwise otherwise the the class class works works in in principle principle in in the the same same way way as as in in 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, but but the the difference difference isis only only that that they they store store the the objects objects in in aa different different way. way. I’ve I’ve shown shown the the whole whole class class below, below, and and you you should should study study the the code code and and how how the the class class PersonDB PersonDB isis used: used: package history; import java.util.*; import java.io.*; public class Persons implements Iterable { private static String path; private ArrayList list; public Persons(String path) throws IOException { this.path = path; load(); } public Iterator iterator() { return list.iterator(); }

Download free eBooks at bookboon.com 29 29

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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(); } }

Download free eBooks at bookboon.com 30 30

Click on the ad to read more

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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));

Download free eBooks at bookboon.com 31 31

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

}

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(); } }

Download free eBooks at bookboon.com 32 32

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

}}

java.io java.Io java.Io

private static static String[][] String[][] navne navne == {{ private "Gorm den den Gamle", Gamle", "", "", "958" "958" }, }, {{ "Gorm { "Harald Blåtand", "958", "986" }, { "Harald Blåtand", "958", "986" }, …… }; };

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

PROBLEM PROBLEM 1 1 You must must in in this this problem problem write write aaa program program similar similar to to the the program program above, above, but but the the program program You You must in this problem write program similar to the program above, but the program must instead instead maintain maintain aaa product product database. database. A A product product is is described described with with four four fields: fields: must must instead maintain product database. A product is described with four fields: public class class Product Product public { { private int pnr; private int pnr; private String name; private String name; private short units; private short units; private float price; private float price;

// // // // // // // //

product number product number product name product name units in stock units in stock unit price unit price

Download free eBooks at bookboon.com 33 33 33

Click on the ad to read more

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 product’s 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 program’s 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 {}

Download free eBooks at bookboon.com 34 34

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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 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 class’s class’s 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 into should also note that the first 4 bytes in the file is a signature, which you must take into account account when when determining determining the the location location of of each each record. record.

Download free eBooks at bookboon.com 35 35

JAVA 5: FILES AND JAVA IO

java.io

The application’s 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.

Download free eBooks at bookboon.com 36

Click on the ad to read more

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 file’s 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 = (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; }

360° thinking

.

360° thinking

.

360° thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discoverfree theeBooks truth atatbookboon.com www.deloitte.ca/careers Download

Click on the ad to read more

51 51

Dis

JAVA 5: FILES AND JAVA IO JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO JAVA

} }

public String String public { { return name name return } }

java.io java.Io java.Io

toString() toString() + String.format(", String.format(", %d %d years", years", getAge()); getAge()); +

The class class has has four four instance instance variables. variables. It It can can be be serialized serialized as as the the first first variable variable has has the the type type The String, which which isis Serializable, Serializable, the the other other isis of of the the type type Calendar Calendar (and (and must must represent represent aa person’s person’s String, date of of birth) birth) isis also also Serializable, Serializable, while while the the third third isis aa double double (and (and all all variables variables of of aa primitive primitive date types can can immediately immediately be be serialized). serialized). The The variable variable will will represent represent an an hourly hourly rate. rate. The The last last types variable represents 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 variable serialized, and and the the meaning meaning isis that that you you then then can can specify specify that that variables variables or or objects objects of of any any serialized, reason not not should should be be serialized. serialized. reason The following following method method creates creates aa Person Person object, object, assigns assigns the the person person 20 20 hours, hours, and and then then The prints the 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 prints ObjectOutputStream (which (which as as parameter parameter has has an an OutputStream) OutputStream) and and the the method method writeObject(): writeObject(): ObjectOutputStream private static static void void test09() test09() private { { try (ObjectOutputStream (ObjectOutputStream stream stream = = try new ObjectOutputStream(new ObjectOutputStream(new FileOutputStream("person"))) FileOutputStream("person"))) new { { Person pers pers = = Person new Person("Carlo Jensen", new new GregorianCalendar(1949, GregorianCalendar(1949, 0, 0, 23), 23), 225); 225); new Person("Carlo Jensen", pers.add(20); pers.add(20); print(pers); print(pers); stream.writeObject(pers); stream.writeObject(pers); } } catch (IOException (IOException ex) ex) catch { { System.out.println(ex); System.out.println(ex); } } try (ObjectInputStream (ObjectInputStream stream stream = = try new ObjectInputStream(new FileInputStream("person"))) new ObjectInputStream(new FileInputStream("person"))) { { Person pers pers = = (Person)stream.readObject(); (Person)stream.readObject(); Person print(pers); print(pers); } } catch (ClassNotFoundException (ClassNotFoundException ex) ex) catch { { System.out.println(ex); System.out.println(ex); } }

Download free eBooks at bookboon.com 52 52 52

JAVA 5: FILES AND JAVA IO JAVA 5: 5: FILES AND AND JAVA IO IO JAVA JAVA 5: FILES FILES AND JAVA JAVA IO

} } }

java.io java.Io java.Io java.Io

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

Afterthe theobject objectisis is serialized serializeditit it isdeserialized deserializedagain againwith withan anObjectInputStream, ObjectInputStream,after afterwhich whichitit it After After After the the object object isserialized serialized itisis is deserialized deserialized again again with with an an ObjectInputStream, ObjectInputStream, after after which which it isprinted printedon onthe thescreen. screen.The Theobject objectisis is read readwith withreadObject(), readObject(),and andyou youshould shouldnote notethe theneed need isis is printed printed on on the the screen. screen. The The object object isread read with with readObject(), readObject(), and and you you should should note note the the need need foraaatypecast. typecast.IfIf Ifitit itnot notisis ispossible, possible,you youget getaaaClassNotFoundException. ClassNotFoundException.The Theprint() print()method methodis:is: is: for for typecast. not possible, you get ClassNotFoundException. The print() method for a typecast. If it not is possible, you get a ClassNotFoundException. The print() method is: private static static void print(Person print(Person pers) private private static void void print(Person pers) pers) { { { System.out.println(pers); System.out.println(pers); System.out.println(pers); System.out.println("Pay: " " + pers.getPay()); pers.getPay()); System.out.println("Pay: 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, Jensen, Carlo Carlo Jensen, Pay: 4500.0 Pay: Pay: 4500.0 4500.0 Carlo Jensen, Jensen, Carlo Carlo Jensen, Pay: 0.0 Pay: Pay: 0.0 0.0

68 years years 68 68 years 68 years years 68 68 years

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

Thefollowing followingmethod methodalso alsoserialize serializePerson Personobjects objects(three (threeobjects), objects),and andshould shouldshow showthat thatitit it The The The following 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 possibletoto to serialize serializemultiple multipleobjects objectsinin in the thesame samefile: file: isis is possible possible toserialize serialize multiple multiple objects objects inthe the same same file: file: private static static void test10() test10() private private static void void test10() { { { Person[] pers pers = { { Person[] Person[] pers = = { new Person("Carlo Jensen", new new GregorianCalendar(1949, 0, 0, 23), 225), 225), new new Person("Carlo Person("Carlo Jensen", Jensen", new GregorianCalendar(1949, GregorianCalendar(1949, 0, 23), 23), 225), new Person("Gudrun Person("Gudrun Andersen", new new GregorianCalendar(1963, 10, 10, 3), 325), 325), new new Person("Gudrun Andersen", Andersen", new GregorianCalendar(1963, GregorianCalendar(1963, 10, 3), 3), 325), new Person("Abelone Sørensen", new GregorianCalendar(1972, 3, 13), 375) }; new new Person("Abelone Person("Abelone Sørensen", Sørensen", new new GregorianCalendar(1972, GregorianCalendar(1972, 3, 3, 13), 13), 375) 375) }; }; try (ObjectOutputStream (ObjectOutputStream stream stream = = try try (ObjectOutputStream stream = new ObjectOutputStream(new ObjectOutputStream(new FileOutputStream("personer"))) new new ObjectOutputStream(new FileOutputStream("personer"))) FileOutputStream("personer"))) { { { for (Person (Person p : : pers) stream.writeObject(p); stream.writeObject(p); for for (Person p p : pers) pers) stream.writeObject(p); } } } catch (IOException (IOException ex) catch catch (IOException ex) ex) { { { System.out.println(ex); System.out.println(ex); System.out.println(ex); } } }

Download free eBooks at bookboon.com 53 53 53 53

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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); } NY026057B 4 TMP PRODUCTION 12/13/2013 catch (IOException ex) ACCCTR00 6x4 { PSTANKIE System.out.println(ex); gl/rv/rv/baf Bookboon Ad Creative } }

All rights reserved.

© 2013 Accenture.

Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon

Download free eBooks at bookboon.com 54 54

Click on the ad to read more

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 Sørensen", 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;

Download free eBooks at bookboon.com 55

JAVA JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO JAVA 5: FILES AND JAVA IO

java.io 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 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 You should note that the class is not defined Serializable, but objects of this type can still be serialized serialized because because the the base base class class is is Serializable: Serializable: be 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.

Download free eBooks at bookboon.com 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 by by yourself yourself how how the the objects objects must must be be serialized serialized and and 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 couldalso alsobe beother otherreasons. reasons.The Theprocess processisisquite quitesimple, simple,since sincethe theclass classititisisdesired desired to to serialize serialize asas usual usual must must be be 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; }

The Wake the only emission we want to leave behind

.QYURGGF'PIKPGU/GFKWOURGGF'PIKPGU6WTDQEJCTIGTU2TQRGNNGTU2TQRWNUKQP2CEMCIGU2TKOG5GTX 6JGFGUKIPQHGEQHTKGPFN[OCTKPGRQYGTCPFRTQRWNUKQPUQNWVKQPUKUETWEKCNHQT/#0&KGUGN6WTDQ 2QYGTEQORGVGPEKGUCTGQHHGTGFYKVJVJGYQTNFoUNCTIGUVGPIKPGRTQITCOOGsJCXKPIQWVRWVUURCPPKPI HTQOVQM9RGTGPIKPG)GVWRHTQPV (KPFQWVOQTGCVYYYOCPFKGUGNVWTDQEQO

Download free eBooks at bookboon.com 57 57

Click on the ad to read more

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

java.io 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 ObjectInputStream(new FileInputStream("name"))) FileInputStream("name"))) new { { Name name name == (Name)stream.readObject(); (Name)stream.readObject(); Name System.out.println(name); System.out.println(name); } }

Download free eBooks at bookboon.com 58 58 58

JAVA 5: FILES AND JAVA IO JAVA JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO

} }

java.io java.Io java.Io

catch catch (ClassNotFoundException (ClassNotFoundException ex) ex) { { System.out.println(ex); System.out.println(ex); } } catch (IOException (IOException ex) ex) catch { { 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 You should note that the serialization and deserialization syntactically happens exactly Youshould shouldnote notethat thatthe theserialization serializationand anddeserialization deserializationsyntactically syntacticallyhappens happensinin inexactly exactly the same way. It’s just some other methods that are performed. the the same same way. way. It’s It’s just just some some other other methods methods that that are are performed. performed. EXTERNALIZABLE EXTERNALIZABLE EXTERNALIZABLE

ItIt also possible completely self address how the objects should be serialized and It isis is also also possible possible completely completely self self toto to address address how how the the objects objects should should be be serialized serialized and and deserialized, and again could performance be a reason. The class that should be serialized deserialized, and again could performance be a reason. The class that should be serialized deserialized, and again could performance be a reason. The class that should be serialized must must instead Serializable implement the interface Externalizable, which defines two must instead instead ofof of Serializable Serializable implement implement the the interface interface Externalizable, Externalizable, which which defines defines two two methods writeExternal() and readExternal(): methods methods writeExternal() writeExternal() and 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; } }

Download free eBooks at bookboon.com 59 59 59

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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(); }

30 FR da EE ys tria

SMS from your computer ...Sync'd with your Android phone & number

l!

Go to

BrowserTexting.com

and start texting from your computer!

...

Download free eBooks at bookboon.com 60 60

BrowserTexting

Click on the ad to read more

JAVA JAVA5: 5:FILES FILESAND ANDJAVA JAVAIO IO

java.io java.Io

These These methods methods must must then then 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 by by 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); } }

Download free eBooks at bookboon.com 61 61

JAVA JAVA5:5:FILES FILESAND ANDJAVA JAVAIO IO

java.io java.Io

2.5 2.5 CHARACTER CHARACTERSTREAMS STREAMS There Therealso alsoisisaafamily familyofofclasses classesthat thatare areused usedtotostream streamaasequence sequenceofofcharacters charactersand andthus thusaa text. text.InInfact, fact,they theyare arefar farmore moreoften oftenneeded neededthan thandirectly directlystream streamaasequence sequenceofofbytes bytes(and (and hence hencethe theraw rawdata). data).InInJava Javaisistext textororcharacters charactersrepresented representedasas22bytes bytesunicodes, unicodes,but butwhen when they theyare arestreamed 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 frequentlyused used characters, characters,including includingnational nationalcharacters charactersoccupies occupies22orormore morebytes. bytes.The Thegoal goalisissimple simpletoto reduce reducethe thenumber numberofofbytes bytessent sentover overaastream. stream.Stream Streamclasses classestotocharacters charactersmust musthandle handlethe the necessary necessaryconversion conversionthat thathappens happenstransparently transparentlywithout withoutthe theprogrammer’s programmer’sinvolvement involvement––atat least leastasaslong longthat thatthe theprogram programshould shouldnot notbe beused usedanywhere anywhereininthis thisworld. world.Strictly Strictlyspeaking, speaking, not notthe thesame sameencoding encodingare areused usedeverywhere everywherebut butthe theentire entireWestern Westernworld worlduses usesthe thesame same encoding. encoding.IfIfyou youneed needinternationalization, internationalization,ititisispossible possibletotospecify specifythe theencoding encodingtotobe beused, used, but butotherwise otherwisestream streamclasses classesuses usesan anencoding encodingbased basedon onthe themachine’s machine’slocal 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 Blåtand\n"); writer.write("Svend Tveskæg\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); } }

Download free eBooks at bookboon.com 6262

JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO JAVA

java.Io java.io

The methods 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 The buffer whose 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 buffer with text 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 with here you 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 here perceive the the file file as as line-oriented: line-oriented: perceive private static void test16() { try (BufferedWriter writer = new BufferedWriter(new FileWriter("names"))) { writer.write("Gorm den Gamle"); writer.newLine(); writer.write("Harald Blåtand"); writer.newLine(); writer.write("Svend Tveskæg"); } catch (IOException ex) { System.out.println(ex); } try (BufferedReader reader = new BufferedReader(new FileReader("names"))) {

Brain power

By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to maintenance. 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

Download free eBooks at bookboon.com 63 63

Click on the ad to read more

JAVA 5: FILES AND JAVA IO JAVA JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO

java.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 above example used FileWriter and FileReader as character-oriented stream classes In the the above above example example III used used aaa FileWriter FileWriter and and FileReader FileReader as as character-oriented character-oriented stream stream classes classes In to files and including BufferedWriter and BufferedReader, but there are other Reader and to files files and and including including BufferedWriter BufferedWriter and and BufferedReader, BufferedReader, but but there there are are other other Reader Reader and and to Writer classes, there most be important: Writer classes, classes, there there most most be be important: important: Writer ----------------------

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

You should also note that FileReader and FileWriter isis wrapper wrapper classes for respectively an You should should also also note note that that aaa FileReader FileReader and and FileWriter FileWriter is wrapper classes classes for for respectively respectively an an You InputStreamReader and an OutputStreamWriter. InputStreamReader and and an an OutputStreamWriter. OutputStreamWriter. InputStreamReader Sometimes itit is isis recommended recommended not to use the FileReader and FileWriter, as they do not allow Sometimes it recommended not not to to use use the the FileReader FileReader and and FileWriter, FileWriter, as as they they do do not not allow allow Sometimes you to enter any Encoding. The same method as above can be written as follows where you you to to enter enter any any Encoding. Encoding. The The same same method method as as above above can can be be written written as as follows follows where where you you you indicates the encoding: indicates the the encoding: encoding: indicates private private static static void void test17() test17() {{ try try (BufferedWriter (BufferedWriter writer writer == new new BufferedWriter( BufferedWriter( new OutputStreamWriter(new FileOutputStream("navne2"), new OutputStreamWriter(new FileOutputStream("navne2"), "ISO-8859-1"))) "ISO-8859-1"))) {{ writer.write("Gorm writer.write("Gorm den den Gamle"); Gamle"); writer.newLine(); writer.newLine(); writer.write("Harald writer.write("Harald Blåtand"); Blåtand"); writer.newLine(); writer.newLine(); writer.write("Svend writer.write("Svend Tveskæg"); Tveskæg"); }} catch catch (IOException (IOException ex) ex) {{ System.out.println(ex); System.out.println(ex); }}

Download free eBooks at bookboon.com 64 64 64

JAVA JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO JAVA 5: FILES AND JAVA IO

} }

java.io 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 this case, case, indicates indicates the the encoding encoding that that itit not not should should be be UTF8 UTF8 but but ISO ISO 8859-1, 8859-1, in in which which In In this case, indicates the encoding that it not should be UTF8 but ISO 8859-1, in which all characters characters are are encoded encoded as as aa single single byte. byte. The The main main use use of of this this option option isis that that you you may may all all characters are encoded as a single byte. The main use of this option is that you may need to 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 need to read text files created with another program and then not may be UTF8 encoded.

PROBLEM 22 PROBLEM PROBLEM 2 The folder folder to to this this book book contains contains three three text text files files called called The The folder to this book contains three text files called 1. regions, 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. 1. regions, that contains a line for each Danish region where a line consists of a region number and and the the name name of of the the region region separated separated by by commas commas number number and the name of the region separated by commas 2. municipalities, municipalities, that that contains contains aa line line for for each each Danish Danish municipality, municipality, where where the the line line 2. 2. municipalities, that contains a line for each Danish municipality, where the line consists of of the the municipality’s municipality’s number, number, the the name name og og the the municipality municipality and and the the consists consists of the municipality’s number, the name og the municipality and the number of 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 number of the region that the municipality belongs and where the three fields are separated by by commas commas separated separated by commas 3. zipcodes, zipcodes, that that contains contains aa line line for for each each zip zip code, code, where where the the line line consists consists of of the the postal postal 3. 3. zipcodes, that contains a line for each zip code, where the line consists of the postal code and and the the city city name, name, followed followed by by one one or or more more municipality municipality numbers numbers indicating indicating code code and the city name, followed by one or more municipality numbers indicating themunicipalities municipalitiesthat thatuse usethis thiszip zipcode codeand andwhere whereall allfields fieldsare areseparated separatedby bycommas commas the the municipalities that use this zip code and where all fields are separated by commas You must 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 You must now create a new project in NetBeans, as you for example can call for Denmark. You must 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 You must then add the following three interfaces to your project and write classes that implements these these interfaces: interfaces: implements 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. */ */

Download free eBooks at bookboon.com 65 65 65

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

java.io java.Io

public interface IRegion extends Comparable, Iterable, 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 */

> Apply now redefine your future

- © Photononstop

AxA globAl grAduAte progrAm 2015

axa_ad_grad_prog_170x115.indd 1

19/12/13 16:36

Download free eBooks at bookboon.com 66 66

Click on the ad to read more

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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 mønsteret definerer at man kan iterere over denne kommunes postnumre. */ public interface IMunicipality extends Comparable, Iterable, java.io.Serializable { /** * @return The municipality's number */ public int getMnr(); /** * @return The municipality's name */ public String getName();

Download free eBooks at bookboon.com 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);

Download free eBooks at bookboon.com 68 68

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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, Iterable, java.io.Serializable { /** * @return The code */ public String getCode(); /** * @return The city */ public String getCity();

LIGS University based in Hawaii, USA is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:

▶▶ enroll by October 31st, 2014 and ▶▶ save up to 11% 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.

Download free eBooks at bookboon.com 69 69

Click on the ad to read more

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

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.*;

Download free eBooks at bookboon.com 70 70

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

java.io java.Io

public class Repository implements Serializable { private static String filename = "denmark"; private static Repository instance = null; private List regions; private List municipalities; private List zipcodes;

// filename to serialization the data // variable to an instance // to regions // to municipalities // 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 itrZipcode() { }

Download free eBooks at bookboon.com 71 71

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

java.io java.Io

/** * @return Iterator, that iterates til regions. */ public Iterator itrRegioner() { } /** * @return Iterator, that iterates til municipalities. */ public Iterator itrMunicipality() { }

}

private Repository() { }

The class is defined Serializable, and the private constructor must start by deserialize The class is defined Serializable, and the private constructor must start by deserialize object of the type Repository. Is it not possible, the constructor instead must initialize object of the type Repository. Is it not possible, the constructor instead must initialize 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.

Download free eBooks at bookboon.com 72 72

an an an an

Click on the ad to read more

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 municipality’s name contains the search text for municipality and the municipality uses the zip code that matches the search text for city name.

Download free eBooks at bookboon.com 73

JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO JAVA

java.Io java.io

2.6 TEXT SCANNER 2.6 During data 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 During for anything anything other other than than simply simply entering entering data. data. Basicly Basicly aa Scanner Scanner is is an an object object that that scans scans aa for character-oriented stream stream and and divides divides the the stream stream into into tokens. tokens. Consider Consider as as an an example example the the character-oriented following method: method: following private static void test18() { try (BufferedWriter writer = new BufferedWriter(new FileWriter("names"))) { writer.write("Gorm den Gamle"); writer.newLine(); writer.write("Harald Blåtand"); writer.newLine(); writer.write("Svend Tveskæg"); } 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 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 the file, 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, the which scans 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 which at each each line. line. The The result result is: is: at Gorm den Gamle Harald Blåtand Svend Tveskæg

Download free eBooks at bookboon.com 74 74

JAVA 5: FILES AND JAVA IO JAVA 5: FILES AND JAVA IO

java.Io java.io java.Io

By default default tokens tokens are are separated separated by by aa white white spaces, spaces, which which are are space, space, tab tab and and newline. newline. By Therefore, the 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 Therefore, be separated, 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 be used to to separates separates tokens, tokens, and and the the result result is: is: used Gorm den Gamle Gorm den Gamle Harald Blåtand Harald Blåtand Svend Tveskæg Svend Tveskæg

The parameter 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 The parameter to the method useDelimiter() is string that can be any regular expression, and you 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 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 – the The The class Scanner also has methods that can convert tokens to the primitive types –– if ifif the the tokens has has legal legal values. values. Otherwise Otherwise the the conversion conversion throws throws an an exception. exception. Consider Consider as as an an tokens tokens has legal values. Otherwise the conversion throws an exception. Consider as an example the the following following method: method: example 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();

Download free eBooks at bookboon.com 75 75 75

Click on the ad to read more

JAVA 5: FILES AND JAVA IO JAVA JAVA 5: 5: FILES FILES AND AND JAVA JAVA IO IO

java.io java.Io java.Io

for for (int (int ii == 0; 0; ii