Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dynamic Arrays Dynamic arrays are arrays that are re- allocated to a larger size. –See Eck Section 8.3 for details. –For instance, what happens with the.

Similar presentations


Presentation on theme: "Dynamic Arrays Dynamic arrays are arrays that are re- allocated to a larger size. –See Eck Section 8.3 for details. –For instance, what happens with the."— Presentation transcript:

1 Dynamic Arrays Dynamic arrays are arrays that are re- allocated to a larger size. –See Eck Section 8.3 for details. –For instance, what happens with the following? int numbers[] = {5, 4, 6, 7, 3, 4, 1, 1, 4}; int finalIndex = numbers.length + 5; for (int i = 0; i < finalIndex; i++) System.out.println(“number is: “ + numbers[i]);

2 Dynamic Arrays –A dynamic array implementation would look like: int numbers[] = {5, 4, 6, 7, 3, 4, 1, 1, 4}; int finalIndex = numbers.length + 5; for (int i = 0; i < finalIndex; i++) { if (i == numbers.length) { int temp[] = new int[numbers.length * 2]; for (int j = 0; j < numbers.length; j++) temp[j] = numbers[j]; numbers = temp; } // end of if System.out.println(“number is: “ + numbers[i]); } // end of for

3 I/O Streams What is a stream when programming? –import java.io.*; What basic types of streams are there? –The parent classes are OutputStream and InputStream.

4 I/O Streams What type of data can be transported over streams? When must you use streams? –Data from files. –Data over a network. –Data between threads.

5 I/O Streams A byte stream works with data that is machine formatted. –1110 A character stream works with data that is human readable. –15 –Most human’s preferences are to work with this type of data.

6 Byte Streams –Using a byte stream will make your program faster. The data is already in a format that the program can work with. The data is simply copied to and from the streams. The primary byte stream classes are InputStream and OutputStream. Why would this type of stream be important? System.in and System.out are both byte streams.

7 Byte Streams The InputStream class reads one byte at a time (a number between 0 and 255) using: public int read() throws IOException When the end of the input is received, this function returns a –1. What happens when this function encounters an error? –What must then be included in your program?

8 Byte Streams The InputStream provides additional methods that permit reading multiple bytes at one time. –It does not provide the capability to read a series of bytes directly into an int, double, string, etc.

9 Byte Streams The OuputStream class writes one byte at a time (a number between 0 and 255) using: public void write(int b) throws IOException

10 Byte Streams The OutputStream provides additional methods that permit writing multiple bytes at one time. –Again, it does not provide the capability to write a series of bytes as an int, double, string, etc.

11 Character Streams –A character stream should be used if humans must be able to understand the data while working with the program. The primary character stream classes are Reader and Writer. Character streams translate the human formatted data into binary data. –Java uses Unicode and therefore can understand and translate many languages in the world including non- western languages.

12 Character Streams Typically you will not directly use the Reader and Writer classes. –You will use subclasses for these classes. –The Reader and Writer classes allow you to read and write char values only.

13 PrintWriter Class The PrintWriter class is a subclass of the Writer class. –To use the PrintWriter class you must wrap the Writer class in it as follows: PrintWriter outputData = new PrintWriter( new Writer() ); –In addition to creating a PrintWriter as above, one may also be constructed with an OutputStream as the parameter.

14 PrintWriter Class The PrintWriter class provides print and println functions for each of the primitive data types. –These functions do not throw exceptions. –This does not mean that errors can not happen when writing data. The checkError() function will return true if there was an error during writing.

15 DataOutputStream Class The DataOutputStream enables a program translate primitive data types to binary data for writing to an OutputStream. –This class contains methods like: writeDouble(double x) and writeInt(int x). –To create an instance of a DataOutputStream : DataOutputStream dataOut = new DataOutputStream( new OutputStream() );

16 DataInputStream Class The DataInputStream class permits binary data to be read directly into a primitive data type from an InputStream. –The class contains methods such as: readInt(), readChar(), and readUTF() –To create an instance of a DataInputStream : DataInputStream dataIn = new DataInputStream( new InputStream() );

17 Misc. Data written by the DataOutputStream class is guaranteed to be in a format that can be read by the DataInputStream class.

18 TextReader Class The TextReader class provides similar capabilities as the PrintWriter class. –NOTE: The TextReader class is NOT a standard Java class. It was written by Eck. Prof. Jenks expects that you will use the TextReader class for your assignments. Keep in mind, that this class will not be available in the real world!

19 TextReader Class The TextReader class is a subclass of the Reader Class. TextReader readText = new TextReader ( new Reader() ); –An InputStream can also be wrapped into a TextReader. TextReader readInput = new TextReader ( System.in );

20 TextReader Class The TextReader class may throw exceptions. –Recall that the PrintWriter class does not throw exceptions. –By default the TextReader class will throw exceptions of the type TextReader.Error –The exceptions may be turned off by calling the TextReader ’s checkIO (false) method. To check for errors when the exceptions are turned off call the checkError() function.

21 Writing and Reading Objects Can we use the previous capabilities to read or write object instances? –Why or why not?

22 Writing and Reading Objects The ObjectInputStream and ObjectOutputStream classes can solve our dilemma. –Both of these classes can throw exceptions. So your code must do what???

23 Reading an Object ObjectInputStream inObj = new ObjectInputStream( new InputStream() ); –The method for reading an object is: Object newObj = inObj.readObject(); What if you want to read an object of type Car rather than type Object ? What is a potential problem of reading the wrong type of object?

24 Reading an Object –To verify that an Object is the type you expect before you type cast it, you should always use the following: Car newCar; if ( newObj instanceof Car) { newCar = newObj; }

25 Writing Objects ObjectOutputStream outObj = new ObjectOutputStream( new OutputStream() ); –The method for reading an object is: Car outputCar = new Car(“audi”, “A4”, “silver”); outObj.writeObject( (Object) outputCar );

26 Files Why do we need files? What are the components of a file? What types of files are there (with regard to accessing data in the file)?

27 Files Files in Java –Are sequential streams of bytes. –End with either an end-of-file marker or at a specific byte number recorded in a system maintained administrative data structure. –What happens when a stream is opened? –Should you close a file when you are done using it?

28 Files Some interesting notes about files: –Opening a file for writing will erase any previous data stored into that file. –A file can be opened for writing using the append option, in which case the original contents of the file will not be lost. Any new data will be placed at the end of the file.

29 Applets and Files Applets that are downloaded over a network connections are not permitted to access files on your computer. –This is a security violation. –Stand alone programs on a particular computer can access files on that particular computer.

30 Files and machine format data Java includes two classes that permit reading and writing of machine format information to and from files. –FileInputStream and FileOutputStream –In order to append data to an existing file during writing, instantiate the FileOutputStream as follows: FileOutputStream outFile = new FileOutputStream( “fileName”, true);

31 FileWriter Class The FileWriter Class is used to write human readable data to a file. –Exception handling is required when using this class.

32 FileWriter Class FileWriter outData; try { outData = new FileWriter( “output.txt” ); } catch (IOException e) { System.err.println(“Exception: “ + e); }

33 FileWriter Class The FileWriter Class contains only primitive read methods so it is common to wrap it in something like the PrintWriter class.

34 FileWriter Class PrintWriter outData; try { outData = new PrintWriter( new FileWriter( “outputData.txt” ) ); } catch (IOException e) { System.err.println( “Exception: “ + e ); }

35 FileReader Class The FileReader class is similar to the FileWriter class except that it is used for reading files. –Since you have the TextReader class, you should wrap the FileReader class inside of it.

36 FileReader Class TextReader inData; try { inData = new TextReader( new FileReader( “inputData.txt” ) ); } catch (FileNotFoundException e) { System.err.println( “Exception: “ + e ); }

37 File Names If a program needs to access a file in the current directory, then the program only needs the name of the file. If the program needs to access a file in a directory other than the current directory, then the program needs the appropriate path name to the file directory.

38 Path Names An absolute path name uniquely identifies a file from all other files on the system. ~jadams/UH/CSCI3134.ppt A relative path name tells the program how to find the file from the current directory.../../UH/CSCI3134.ppt

39 Path Names Remember that path names vary from one type of machine to another. –It is best to use simple file names.

40 FileDialog Class The FileDialog Class can be used to provide a platform independent file dialog box. –It can be used to create a dialog box that opens files for reading as well as create a dialog box for opening files for writing.

41 File Class The File Class can be used to combine a path name and a file name into one entity that can be used to open the file. File file = new File(directoryPath, fileName); The File Object can then be used to create a PrintWriter. PrintWriter out = new PrintWriter( new FileWriter( file ) );

42 File Class An object of type File represents a file name not an actual file. –There are various methods in the class that allow the program to determine if the fileName is a file, a directory, if the file exists, etc.

43 Some Examples FileCopy.java ReverseFileJAA.java WordList.java TrivialEdit.java

44 Streams and Networks A network is really just another input or output source for data to or from a program. –Java allows the use of input and output streams to process network communications. Aside from importing the java.io.* package your program must also import the java.net.* package.

45 Networks There are two types of network I/O in Java. –At a high level there is URL WWW based networks. What type of Java programs would you expect would use this network capability? –At a lower level there is socket communications.

46 Networks In order to work with either type of network, a program must connect to the network.

47 URL Class The URL Class is used to work with resources in the WWW. –An instance of the URL Class represents a URL address. –This class instance can be used to create a connection between your computer and the resource at the specified URL.

48 URL Class The getContent() method returns an instance of type Object containing the text file, image, or other resources found on the web at the given URL.

49 URL Class The Applet class contains the method getDocumentBase() that returns a URL object which represents the location from which the HTML page containing the applet was downloaded. –This information can be used to go back and access other information at the same location.

50 URL Class The URL instance can be used to create a stream to access data at that location. URL address = new URL( getDocumentBase(), “data.txt” ); InputStream in = address.openStream(); –The openStream() method opens the network connection. –Typically you will find the InputStream wrapped inside a DataInputStream or TextReader class. Why?

51 URL Class In addition to the typical IO exceptions there are now a set of new exceptions that can be thrown related to the network capabilities. –For example, Web browsers are typically configured such that an applet is forbidden to make a network connection to any computer other than the computer that the applet was downloaded from. Attempting to do so would cause a SecurityException.

52 URL Class Example: –URLExampleApplet.java

53 TCP/IP The Internet Protocol and Transmission Control Protocol (TCP/IP) are used to provide process to process communication over the internet. –This is typically called socket communications. –When using this protocol each program creates a socket and the two sockets must be connected to each other. Example, using the telephone.

54 TCP/IP There are two ends to the connection, a client and a server. The server creates a listening socket that waits passively for a connection request from another socket. The client creates a socket and sends a connection request to the server. Think of a help desk.

55 TCP/IP TCP/IP connections require both an IP address and a port number in order to establish a connection.

56 IP Addresses In order to establish a TCP/IP communications protocol, an IP address is required. –There is an IP address for every computer on the internet. This address is unique identifies each computer. A domain name is associated with the IP address. –sfax.cs.rit.edu

57 Port Numbers Each computer has multiple port numbers that permit multiple network connections at the same time. –A port number is a 16-bit integer. A web server usually uses port 80. Reserved port numbers are between 0 and 1024. A program should use port numbers between 1025 and 65535.

58 Servers A server may have a single client socket or it may service multiple client sockets at the same time. –After a client connects, the server continues to listen for new connections.

59 Servers –The server has one main thread that runs continuously while the server remains running. When a connection request arrives, the server creates a new thread just for that client. The new thread services that client until the connection is lost. No other clients can access that thread. –Servers listen for connections at a particular IP address on a particular port.

60 Clients The client programs are usually much simpler than the server programs. –They tend to request one server connection and have only one main thread. –A client program may request multiple client connections or may even act as a server for a new connection. Give examples.

61 Clients –Clients request connections at a particular IP address on a particular port.

62 Socket Class The Socket Class represents one side of the actual network connection. –A Socket object may be a client issuing a request. –A Socket object may be created by a server to handle a connection request from a client. This permits the server to create multiple sockets and handle multiple connections.

63 Socket Class Constructing a client Socket : String IPAddress = sfax.cs.rit.edu; int portNum = 1048; Socket connection = new Socket( IPAddress, portNum ); –The constructor will block (sit and wait) until a connection is established.

64 ServerSocket Class The ServerSocket Class represents a listening socket that waits for a connection request from clients. –When a request is received, a Socket instance is created to handle the actual communications. The ServerSocket object does not participate in the actual communications.

65 ServerSocket Class Constructing a ServerSocket. ServerSocket server = new ServerSocket( portNum ); –As soon as the server is instantiated, it begins to listen for incoming connection requests. –When the server receives a request, it must accept the request and a Socket must be created. The accept() method will accomplish this goal.

66 Creating Streams Once the connections have been accepted and sockets created, input and output streams must be established to permit the actual communications. InputStream in = server.getInputStream(); OutputStream out = server.getOutputStream();

67 Sockets Example –CLChatServer.java and CLChatClient.java


Download ppt "Dynamic Arrays Dynamic arrays are arrays that are re- allocated to a larger size. –See Eck Section 8.3 for details. –For instance, what happens with the."

Similar presentations


Ads by Google