Java Streams and Files

hedgebornabaloneSoftware and s/w Development

Dec 2, 2013 (3 years and 4 months ago)

77 views


Stream
: an object that either delivers data to its
destination (screen, file, etc.) or that takes data from a
source (keyboard, file, etc.)


it acts as a buffer between the data source and
destination


Input stream
: a stream that provides input to a program


System.in
connects a program to the keyboard


Output stream
: a stream that accepts output from a
program


System.out
connects a program to the screen



Byte based


FileInputStream


FileOutputStream


Character based


Reader


Writer


InputStream, OutputStream, Reader, Writer
are
abstract classes


Need to create an instance of stream of a non
-
abstract type


Can wrap the streams to be more convenience in reading and
writing


ex. wrap FileWriter with processing streams


BufferedWriter


PrintWriter


wrap FileReader with processing streams



BufferedFileReader


Text

Human readable,

Not efficient in
terms of time
and space

(C) 2010 Pearson Education, Inc.
All rights reserved.


The
Reader

and

Writer

abstract

classes are
Unicode two
-
byte, character
-
based streams.


Most of the byte
-
based streams have corresponding
character
-
based concrete
Reader

or
Writer

classes.

A typical codesegment for opening a
textfile for output:


FileWriter out = new FileWriter("test.txt");

BufferedWriter b = new BufferedWriter(out);

//istead of writing a character each step, can write a number of
characte at the same time or write a line


PrintWriter p = new PrintWriter(b);


Or with anonymous (‘unnamed‘) objects:

PrintWriter p = new PrintWriter(


new BufferedWriter(


new FileWriter("test.txt")));


CIS 068


Using
FileReader

is not very efficient. Better

wrap it with BufferedReader:


BufferedReader br =



new BufferedReader(




new FileReader(“name“));


Remark:
BufferedReader

contains the method
readLine()
,
which is convenient for reading textfiles

CIS 068


Display the words separated by any of the following
characters: space, new line (
\
n), period (.) or comma (,).












String inputLine = keyboard.nextLine();

StringTokenizer wordFinder =


new StringTokenizer(inputLine, "
\
n.,");

//the second argument is a string of the 4 delimiters

while(wordFinder.hasMoreTokens())

{


System.out.println(wordFinder.nextToken());

}

Entering "
Question,2b.or 20.
" gives this
output:

Question

2b

or

20


BufferedReader



read(), readLine(), …
none for parsing types


needs
StringTokenizer

then wrapper class methods
like
Integer.parseInt(token
)



Can Use
Scanner

with
File
instead:

Scanner inFile =


new Scanner(new File(“in.txt”));


Scanner inFile = new Scanner(new File(“in.txt"));

int number;

while (inFile.hasInt())


{



number = inFile.nextInt();






// …


}


BufferedReader


readLine()

returns

null


read()

returns

-
1


Scanner


use hasNext() or hasNextLine()
to check first


nextInt(), hasNextInt(),



BufferedReader inFile = …

line = inFile.readline();

while (line != null)

{


// …


line = inFile.readline();

}


-------------------


Scanner inFile = …

while (inFile.hasNextLine())

{


line = infile.nextLine();


// …

}



(C) 2010 Pearson Education, Inc.
All rights reserved.



Character
-
based input and output can be performed
with classes
Scanner

and
Formatter
.


Class
Scanner

is used extensively to input data from the
keyboard. This class can also read data from a file.


Class
Formatter

enables formatted data to be output to any
text
-
based stream in a manner similar to method
System.out.printf
.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.


The constructor with two
String

arguments specifies an
absolute or relative path and the file or directory to
associate with the
File

object.


The constructor with
File

and
String

arguments uses an
existing
File

object that specifies the parent directory of
the file or directory specified by the
String

argument.


The fourth constructor uses a
URI

object to locate the file.


A
Uniform Resource Identifier (URI
)

is a more general form of the

Uniform Resource Locators (URLs)

that are used to locate
websites.


Figure

17.3 lists some common
File

methods. The


http://java.sun.com/javase/6
/
docs/api/j
ava/io/File.html


(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.


A
SecurityException

occurs if the user does not
have permission to write data to the file.


A
FileNotFoundException

occurs if the file
does not exist and a new file cannot be created.


static

method
System.exit

terminates an
application.


An argument of
0

indicates successful program termination.


A nonzero value, normally indicates that an error has occurred.


The argument is useful if the program is executed from a
batch
file

on Windows or a
shell script

on UNIX/Linux/Mac OS X.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.


Scanner

method
hasNext

determines whether the end
-
of
-
file key combination has been entered.


A
NoSuchElementException

occurs if the data being
read by a
Scanner

method is in the wrong format or if
there is no more data to input.


Formatter

method
format

works like
System.out.printf


A
FormatterClosedException

occurs if the
Formatter

is closed when you attempt to output.


Formatter

method
close

closes the file.


If method
close

is not called explicitly, the operating sys
-
tem
normally will close the file when program execution terminates.

Efficient in terms of
time and space



Not readable

Class:
FileInputStream/FileOutputStream


... see
FileReader/FileWriter


The difference:

No difference in usage, only in
input/output format

CIS 068


You can also read and write
objects

to files


Object needs
serialization


If an object is to be serialized:


The class must be declared as public


The class must implement
Serializable


The class must have a no
-
argument constructor


All fields of the class must be serializable: either
primitive types or serializable objects


ObjectOutputStream objectOut =


new ObjectOutputStream(


new FileOutputStream(fileName));



objectOut.writeObject(serializableObject);



objectOut.close( );


ObjectInputStream objectIn =


new ObjectInputStream(


new FileInputStream(fileName));



myObject = (ObjectType)objectIn.readObject( );



objectIn.close( );


try{

while (true)

//readoject

}

catch (EOFException e)

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.

(C) 2010 Pearson Education, Inc.
All rights reserved.


ObjectInputStream

method
readObject

reads
an
Object

from a file.


Method
readObject

throws an
EOFException

if
an attempt is made to read beyond the end of the file.


Method
readObject

throws a
ClassNotFoundException

if the class for the
object being read cannot be located.


A stream is an expensive resource


There is a limit on the number of streams
that you can have open at one time


You should not have more than one stream
open on the same file


You must close a stream before you can open
it again



Remember to close your streams!

(C) 2010 Pearson Education, Inc.
All rights reserved.


Interface
DataOutput

describes a set of methods for
writing primitive types to an output stream.


Classes
DataOutputStream

(a subclass of
FilterOutputStream
) and
RandomAccessFile

each implement this interface
to write primitive
-
type values as bytes.

(C) 2010 Pearson Education, Inc.
All rights reserved.


Class
JFileChooser

displays a dialog that enables
the user to easily select files or directories.