File

currygeckoSoftware and s/w Development

Dec 2, 2013 (3 years and 16 days ago)

79 views

Lecture 8

Input, Output, and Network
Communications

This Lecture


We’ll look at file reading and writing and network
communications.


Files


java.io


streams


java.net
-

h
ow networks work


The Art of Programming Part Eight: working with file
systems and the network


Next week and assignments

java.io.File


Before we can read or write files we need to capture
them. The
File

class represents an external file.


File(String
pathname
)
;


File debts = new File(“e:/myFile.txt”);



However, we must remember that different OSs
have different file systems.


Note the use of a forward slash.


Java copes with most of this, but “e:” wouldn’t work
in UNIX or on a Mac.


Getting file locations: java.awt.FileDialog


Opens a “Open file” box with a directory tree
in it. This stays open until the user chooses a
file or cancels.


Once chosen use FileDialog’s
getDirectory()

and
getFile()

methods to
get the directory and filename.


Getting file locations: java.awt.FileDialog

FileDialog fd = new FileDialog();

fd.setVisible(true);

File f = null;

if

((fd.getDirectory() != null)||( fd.getFile() != null)) {



f = new File(fd.getDirectory() + fd.getFile());

}


Getting file locations: application directory


Each object has a
java.lang.Class

object
associated with it.



This represents the class loaded into the JVM.



One use is to get resources local to the class, i.e. in
the same directory as the .class file.


Class thisClass = getClass();

URL url = thisClass.getResource(“myFile.txt”);



We can then use URL’s
getPath()

to return the
directory as a String for the File constructor.

Useful File methods


exists()
,

canRead()

and
canWrite()


Test whether the file exists and can be read or written to.




createNewFile()

and
createTempFile()


Create a new file, and create a new file in “temp” or “tmp”.



delete()
and

deleteOnExit()



Delete the file (if permissions are correct). Delete when JVM
shutsdown.



isDirectory()

and
listFiles()



Checks whether the File is a directory, and returns an array
of Files representing the files in the directory. Can use a
FilenameFilter

object to limit the returned Files.


Files


java.io


streams


java.net
-

how networks work


The Art of Programming Part Eight: working with
file systems and the network


Next week and assignments


Input and Output


At some point your program will want to get data from an
external source and save data back to it.



This may be over the network, on the local drive or from
hardware.



In Java we use address objects, and input and output
“Streams”.



Streams are objects which represent the external resources
which we can read or write to or from. We don’t need to worry
about “how”.



Input Streams are used to get stuff into the program. Output
streams are used to output from the program.

Streams


Streams based on four abstract classes…



Reader

and
Writer


Work on character streams


that is, treat
everything like it’s going to be a character.



InputStream

and
OutputStream


Work on byte streams


that is, treat everything like
it’s binary data.


Allow us to store efficiently (e.g. ints can be stored
as numbers rather than characters) and store
objects.

Byte streams : general / from files


InputStream


Most
read()

resources sequentially, but
skip()
,
mark()

and
reset()

methods exist. The latter returns
to the
mark()

point.


Read methods return
-
1 at the end of the resource.


Call
close()
method when finished.




FileInputStream(File
fileObject
)


Allows us to read bytes from a file. Usually read until a
condition, which often contains the
read()

as well...




Example

FileInputStream ourStream = null;

File debts = new File(“e:/debts.txt”);

try {


ourStream = new FileInputStream(debts);

} catch (FileNotFoundException fnfe) {


// Do something.

}


The Stream is then usually used in the following fashion:

int c = 0;

while( (c = ourStream.read()) >= 0 ) {


//
Add c to a byte array (more on this shortly).

}

ourStream.close();

Byte streams : general / to files


OutputStream


Used to write to resources.


Each has
write(int)

and
write(byteArray)

method


Also a flush() Method, which you should call at the end of
writing to ensure everything has been sent to the resource.



FileOutputStream(File fileObject)


Used to write to a file if the user has permission.


Overwrites old material in file.



FileOutputStream




(File fileObject, boolean
append
)


Only overwrites if append is
false
.

Byte streams : from arrays


There are cases where we want to write to and
from arrays using streams.



These are usually used as a convenient way of
reading and writing a byte array from other
streams and over the network.




ByteArrayInputStream




ByteArrayOutputStream


Example



F
ileInputStream fin = new FileInputStream(file);

ByteArrayOutputStream b
aos
=

new













ByteArrayOutputStream();


int c;

while((c = fin.read()) >= 0) {


baos.write(c);

}





byte[] b =
baos.toByteArray();



Saves us having to find out size of byte array as
ByteArrayOutputStream has a
toByteArray()

method.

Buffering streams


Sometimes you can’t guarantee that the stream will
work all in one go.


The computer may need to read some other important file in
the middle of your operation.


Your network connection may be bad.



Because of this it is usual to “wrap” streams inside
“buffer” classes.



These save up a store of information that’s a safety
net so you can read or write smoothly.


Buffering streams


BufferedInputStream
,
BufferedOutputStream



You wrap the classes using the buffer’s constructors.


BufferedInputStream(InputStream
inObj
)


BufferedInputStream b =





new BufferedInputStream(ourStream);



You then use them as you would any other stream.


As with an
OutputStream
, you should call the buffer’s
flush()

method at the end of writing


this ensures
all

the
stored info is written.

Other InputStreams and OutputStreams


PrintStream


Was used in Java 1.0 to write characters, but didn’t
do a very good job of it.


Now deprecated as an object, with the exception of
System.out
, which is a static final object of this
type.



RandomAccessFile


Used for reading and writing to files when you need
to write into the middle of files as opposed to the
end.



Object Streams

Serialization


Given that we can read and write bytes to streams,
there’s nothing to stop us writing objects
themselves from the memory to a stream.



This lets us transmit objects across the network
and save the state of objects in files.



This is known as object “serialization”.

Serialization


All objects that can be automatically serialized
implement the
java.io.
Serializable

interface.



If you want to do the serialization yourself (you
crazy kids), your classes should implement
java.io.
Externalizable
.





To serialize an object, you use
ObjectOutputStream
. To unserialize it you use an
ObjectInputStream
.

Character based streams


Two abstract superclasses


Reader

and
Writer
.


For files use…


FileReader

/
FileWriter


For arrays use…


CharArrayReader

/
CharArrayWriter


For buffering use…


BufferedReader

/
BufferedWriter

Example

FileReader fr = new FileReader(“debts.txt”);

BufferedReader br = new BufferedReader(fr);

int lines =
-
1;

String textIn = “ ”;


while (textIn != null) {


textIn = br.readln();


lines++;

}


String[] file = new String[lines];

br.close();

fr = new FileReader(“debts.txt”);

br = new BufferedReader(fr);


for (int i = 0; i <= lines; i++) {


file[i] = br.readln();

}

StreamTokenizer: Bytes to words


Used to break character streams up into
“tokens”, which may, for example, be words.


Reader r = new BufferedReader





(new

InputStreamReader(is));

StreamTokenizer st = new StreamTokenizer(r);

st.resetSyntax();

st.whitespaceChars(0, “ “);

st.nextToken();

String firstWord = st.toString();

Summary


We can represent and explore the files on a
machine with the File class.



To save us having to understand how external info
is produced, java uses streams.



We can read and write bytes to files or arrays.


We can store or send objects using streams.


We can read and write characters to files or arrays.



We should always try and use buffers around our
streams to ensure access.


Files


java.io


streams


java.net

-

How networks work


The Art of Programming Part Eight: working with
file systems and the network


Next week and assignments


Network communications

Last lecture


We saw that, provided there was a server or the
files were local, we could use a URL object to get an
Image or put a webpage in a browser using an
applet.

This lecture


More on addresses.


How to build your own server.


How to get files if not an applet or the files aren’t
images.

Introduction to network communications


Last lecture: communication is via a port, using a protocol.
Several protocols may be involved at once. Most use the
following over the internet…



Internet Protocol (IP)


Used to split data into small chunks called “packets”


Addresses them to the right machine.




Transport Control Protocol (TCP)


Guarantees packets get to their destination.


Controls the route taken and lets computers confirm receipt.


Adds packets back together in the right order.



HyperText Transfer Protocol (HTTP)

java.net.InetAddress


Last lecture we saw the URL class, and how it
encapsulates the location of things on a network.



There is a second address class that deals with
finding
machine

IP address
-
specific information.



java.net.InetAddress



This has no constructors. You create one using the
class’s static methods.

InetAddress creation


InetAddress ina =





InetAddress.getLocalHost();


Returns an InetAddress object representing the
machine the program is running on.



InetAddress ina =



InetAddress.getByName(
hostNameString
);


Returns an InetAddress corresponding to the host
named.



InetAddress[] ina =


InetAddress.getAllByName(
siteNameString
);


Returns an array of InetAddress objects containing
all the servers associated with a given site name.

InetAddress methods


IP addresses are numeric

http://129.11.93.4

will get the School webserver.



However, many machines hold a registry which contains the
numbers and what they’d prefer to be called. This scheme is
called the Domain Name Service (DNS)


http://www.geog.leeds.ac.uk




Methods exist for finding a numerical internet address (IP
address) from the domain name, and vice versa.



These methods might have to do the DNS look
-
up on
another computer on the network
-

this may take some time.

Sockets


Once you have your address, you can then connect
to it.


To do this, we use “sockets”.


These are TCP/IP based stream connections to a
computer port. You need a client and a server.



java.net.Socket


Sends requests to communicate to a port using TCP or
equivalent.


java.net.ServerSocket


Lets you build your own server.


Sits and listens to a port in case something calls it.

Sockets


Socket(InetAddress
ipAdd
, int
port
)


ServerSocket(int
port
)



TCP/IP reserves the first 1024 ports, otherwise you can use
most numbers up to 49151.




A ServerSocket is set to listen with its
accept()
method

which returns a Socket when activated.



Once you have your sockets connected, you can use their
getInputStream()
,
getOutputStream()

and
close()

methods to talk using streams.

Sockets example


On the server…


ServerSocket ss = new ServerSocket(9999);

Socket s = ss.accept();

BufferedInputStream in = s.getInputStream();



Start the program.


Once a connection has been accepted, use the socket to
communicate, not the ServerSocket.



On the client…


Socket s = new Socket(InetServer, 9999);

BufferedOutputStream b = s.getOutputStream();

b.write(aByteArray);

s.close();

Java.net.URLConnection


If you want specific files from an http server which
exists, it’s easier to use a URLConnection object.



URL url = new
URL(“http://www.bbc.co.uk/eastenders/index.html”);


URLConnection urlc = url.openConnection();



Methods include…


getDate()


getContentLength()


getInputStream()


Knowing the number of bytes of a resource (the
ContentLength), and having an InputStream, you
can now read the file.

Class Object Streams

Class thisClass = getClass();

URL url = thisClass.getResource(“debts.txt”);



As well as getting a
URL

Object this way, you can
actually open a Stream to resources.


Class Objects have a
getResourceAsStream

Method, which returns an
InputStream
.


This can be used to read the resource across the
network or into a program from a local file.


Files


java.io


streams


java.net

-

How networks work



The Art of Programming Part Eight:
working with file systems and the
network


Next week and assignments


The Art of Programming: working with
file systems and networks


Never assume the network or file will be there.



Respond to your user if a file is missing, and let them try to
find it.


If it’s one of yours, tell them how to replace it.


When writing for the network, you can compress class files
and associated resources using the
jdk1.6/bin/jar.exe

compressor. This creates “zip”
-
like files that can be read in
java using
java.util.zip
or Class’s

getResource()
.



<APPLET




code = myClass




archive = myJar.jar




width = 300 height = 300>



</APPLET>

The Art of Programming: working
with file systems and networks


Even if the network is running smoothly, never
assume your data will arrive in one go.


Use stream buffers


Always read files until the end of file (EOF) marker.
Most streams return
-
1 or null at this point. This isn’t the
same as reading
-
1.



Always check what other programs, if any, use the
port you are on.


Some networks have “Firewalls”. These are security
devices that sit on Ports and stop some connecting.
Check for them.

Summary


We can represent and explore the files on a
machine with the File class.



To save us having to understand how external info
is produced, java uses streams.



We can read and write bytes to files or arrays.


We can store or send objects using streams.


We can read and write characters to files or arrays.



We should always try and use buffers around our
streams to ensure access.


Summary


Most networks use TCP/IP to communicate.


HTTP gets and sends specific data
-
type requests
on TCP/IP networks.


We can encapsulate specific machine addresses
with an InetAddress object, and specific resources
with a URL object.


Using a URL/URLConnection we can get basic
resource types from a http / web server.


For more complex data and object transmission, we
can set up sockets.


We can use ServerSocket objects to make our own
servers.

Next Lecture


Odds and ends
-


java.lang revisited.


java.util

Practical


Reading and drawing images from file.

Assessment


Come and see me to talk through details.