[text]
I. Abnormal Java is the same as Delphi, not deliberately avoiding it, but waiting for it to remedy later. Delphi's exception handling is simple, it is a statement
Try except // After an abnormality, it is transferred to the event.
Try {} catch (ExceptionType1 E) {file &: // Treatment with / abnormal case 1} Catch (ExceptionType2 E) {file &: // Treatment throw (E) // throwing exception, and Delphi Raise is a matter} To supplement, for most exceptions, if you want to make a clear throw in the normal running program, Java's compiler requires you to want you in advance. Throwing exceptions, otherwise it is not allowed to pass. This task is completed by throws. II. Java input and output flow 2.1 output
System.out.print file &: // This / ut is a static method oh system.rr.Print file &: // err / and out are also standard output, as for what is different, I am not currently not Clear system.err.println 2.2 input
System.in.Read () 2.3 File The operation only requires a few examples of annotations. The first is a program that displays basic information of files.
Import java.io. *; // Turning into and IO related class class fileInfo {file &: // Note / mean / Use the file object to create an instance if (Args.Length> 0) {for (int i = 0; i import java.io. *; class phones {static FileOutputStream fos; public static final int lineLength = 81; public static void main (String args []) throws IOException {byte [] phone = new byte [lineLength]; byte [] name = New byte [LINELENGTH]; INT i; fos = new fileoutputstream ("Phone.NumBers"); while (true) {system.err.println ("Enter a name (Enter 'Done' to quit); Readline Name); if ("DONE" .EqualsignoreCase (New String (Name, 0, 0, 4))) {Break;} System.err.Println ("Enter the Phone Number"); Readline (Phone); for (i = 0; phone [i]! = 0; i ) {fos.write (Phone [i]);} fos.write (','); for (i = 0; Name [i]! = 0; i ) {Fos.Write (Name [i]);} fos.write ('/ n');} fos.close ();} private static void readline (byte line []) THROWS IOEXCEPTION {INT i = 0, b = 0; WHILE ((i <(LineLength-1)) && ((b = system.in.read ())! = '/ N')) {line [i ] = (byte) b;} line [i] = (byte) (0);}} 2.4 The stream is nothing more than two output flows, let us write the input stream, give us a lot of types of input and output flows in the java.io package: 1.FileInputStream and FileOutstream Node stream 2.b ufferedInputStream and BufferedOutputStream filtration flow stream 3.DataInputStream DataOutputStream enhanced filtering and flow 4.PipedInputStream and PipledOutputStream for threads mastered the concept of flow, you can begin to learn the Sockets. Socket on the role of yesterday, I have spoken now We will create a simple communication program to get a substantive understanding of Socket. This program includes two parts, clientserver. The client issues a request to the server, requiring the server on the server. File information. The server will respond to the request, pass the corresponding file information to the client, pass the corresponding file information to the client. First we create a RemoteFileClient class: Import java.io. *; // java.io package provides a tool for reading and writing, is also the only way to communicate with TCP sockets Import java.net. *; // java.net package provides a socket tool. public class RemoteFileClient {protected String hostIp; protected int hostPort; protected BufferedReader socketReader; // object is responsible for reading data protected PrintWriter socketWriter; // responsible for writing the data object file &: // class / constructor has two parameters: remote host One of the IP Address (HostPort). The constructor assigns them to instance variables public remotefileclient (string ahostip, int ahostport) {hostip = ahostip; hostport = ahostport;} public static void main (String [] ARGS) {} file &: // Connection / Remote Server Public Void SetupConnection () {} file &: // Request file information PUBLIC STRING GETFILE (STRING FileNameTogether) {} file &: // From / remote server Distribution () public static void main ("127.0.0.1", 3000); // For convenience of debugging, we put The local server is used as a remote server remoteFileClient.setUpConnection (); // connection. You can't use SetupConnection directly, because it is a non-static variable, after you need to create an instance, you can quote the instance, you can see the diary on my first day, very detailed string filecontents = RemoteFileClient.getFile ("remotefile.txt"); / / Read RemoteFileClient.teardownConnection (); // Disable system.out.println (filecontents); // Output reading content} The step is very clear. So we look at the connection, read, disconnect, how to implement 1. connection public void setUpConnection () {try {Socket client = new Socket (hostIp, hostPort); // Create the Socket object OutputStream outToServerStream = client.getOutputStream (); InputStream inFromServerStream = client.getInputStream (); socketReader = new BufferedReader (new InputStreamReader ( inFromServerStream)); file &: // the / Socket packed into an InputStream BufferedReader so that we can read row socketWriter stream = new PrintWriter (outToServerStream); file &: // the / Socket packed into the OutputStream so that we can send PrintWriter File Request to Server} Catch (UnknownHOSTEXCEPTION E) {System.out.println ("Error Setting Up Socket Connection: Unknown Host AT" Hostip ":" Hostport); File &: // Create an error in the / socket object Processing} Catch (IOException E) {System.out.Println ("Error Setting Up Socket Connection: E); File &: // Abnormal Processing / IO Error}} 2. Read Public String GetFile (String FileNameTogether) {StringBuffer FileLines = New StringBuffer (); // StringBuffer object is also a String object, but is more flexible than it, here is a try {socketwriter.println (filenametoget) used to store read content; socketwriter.flush (); // file Save The address is output to the socketwriter, then clear the buffer, let this address send to String line = null; while ((line = socketreader.readline ())! = Null) files.Append (line "/ n" ); file &: // There is / / already sent to the server, then we must wait for a response, the program is waiting for the server to pass the contents of the files we need.} Catch (IOException E) {System.out.println ("Error Reading from File &:" FileNameToGet);} returniful (); // Don't forget to turn content in buffer to string and return} 3. Disconnect public void tearDownConnection () {try {socketWriter.close (); socketReader.close ();} catch (IOException e) {System.out.println ( "Error tearing down socket connection:" e);}} tearDownConnection () Methods I only close the bufferedReader and PrintWriter created on the INPUTSTREAM and OutputStream created in Socket. This will close the bottom flow of our Socket, so we must capture possible IOException, and now you can summarize the creation steps of the client program 1. Instantize the IP port number to connect to the IP port number (if any problem) Throw an Exception). 2. Get the stream on the socket to read and write. 3. Package the flow package into the instance of BufferedReader / PrintWriter. 4. Read and write the Socket. Specifically, it is transmitted to the server on the Writer to send file address information to the server, in Reader Read the file information from the server 5. Close the open stream. Here is the code list of RemoteFileClient import java.io. *; import java.net *;. public class RemoteFileClient {protected BufferedReader socketReader; protected PrintWriter socketWriter; protected String hostIp; protected int hostPort; public RemoteFileClient (String aHostIp, int aHostPort) {hostIp = aHostIp; hostPort = aHostPort;} public String getFile (String fileNameToGet) {StringBuffer fileLines = new StringBuffer (); try {socketWriter.println (fileNameToGet); socketWriter.flush (); String line = null; while ((line = socketReader.readLine ()) ! = null) FileLines.Append (line "/ n");} catch (ioexception e) {system.out.println ("Error Reading from File &: FileNameTogether);} Return FileLines.toString ();} public static void main (String [] args) {RemoteFileClient remoteFileClient = new RemoteFileClient ( "127.0.0.1", 3000); remoteFileClient.setUpConnection (); String fileContents = remoteFileClient.getFile ( "RemoteFile.txt"); remoteF ileClient.tearDownConnection (); System.out.println (fileContents);} public void setUpConnection () {try {Socket client = new Socket (hostIp, hostPort); OutputStream outToServerStream = client.getOutputStream (); InputStream inFromServerStream = client.getInputStream (); socketReader = new BufferedReader (new InputStreamReader (inFromServerStream)); socketWriter = new PrintWriter (outToServerStream);} catch (UnknownHostException e) {System.out.println ( "Error setting up socket connection: unknown host at" hostIp ": hostport); } catch (ooException e) {system.out.println ("Error Setting Up Socket Connection: E);}} PUBLIC VOID TEARDOWNECTION () {SocketWriter.Close (); socketReader.close ();} catch IOEXCEPTION E) {system.out.println ("Error Tearing Down Socket Connection:" E);}}} Ok, now how to write the server-side programs. Create a RemoteClientServer class: import java.io. *; Import Java .net *;. public class RemoteFileServer {protected int listenPort = 3000; public static void main (String [] args) {} public void acceptConnections () {} public void handleConnection (Socket incomingConnection) {}} Like client, First introduced Java.io.io.i into java.net. Next, give us an instance variable to save the port, and we listen to the entered connection from the port. By default, the port is 3000. Acceptconnections () will allow the client to connect to the server handleConnection () is responsible for interacting with the client Socket to send the content of the file you requested to the client. First see main () Public static void main (string [] args) {remoteFileServer Server = new remoteFileserver (); server.acceptconnections ();} is very simple, because the main function is nothing more than letting the server enters the listening state, so call acceptConnection () directly (). Yes, you must first create an instance of RemoteFileServer () instead of calling directly. Then how the server listens to the client through AcceptConnection ()? And if you have heard it, what is it? Let's see Public void acceptConnections () {Try {ServerSocket Server = new serversocket (listen); // corresponds to the client's socket, in the server side, we need a Serversocket object, the parameter is the port number socket incomingConnection = null; // creation A client's socket variable to receive the socket while (true) {incomingConnection = Server.Accept (); // call the serverSocket from the client monitor to start listening, handleconnection;} File &: // Do not / disconnect a connection request, then pay it to the Handleconnection process} catch (bindexcection e) {system.out.println ("Unable to bind to port" listenport);} catch (ooException E) {System.out.println ("Unable to instantiate a serversocket on port:" listenport);}} Whenever you create a serversocket that cannot be bound to the specified port (probably because of any other control of this port) The Java code will throw an error. So here we have to capture possible BindException. At the same time, as in the client end, we must capture ioException, which will be thrown when we try to accept the connection on the ServerSocket. You can set the timeout for the ACCEPT () call to avoid the actual long-term wait by calling setsotimeout () to avoid the actual wait. Calling setsotimeout () will throw the Accept () to throw the most critical processing after designating the occupancy time in HandleConnection (), which has been connected to the client's socket, and reads the client's request and responds from the Socket. public void handleConnection (Socket incomingConnection) {try {OutputStream outputToSocket = incomingConnection.getOutputStream (); InputStream inputFromSocket = incomingConnection.getInputStream (); file &: // First / obtaining first stream associated with Socket outputToSocket and InputStream file &: // which / outputToSocket is to be returned to the client Socket stream file &: // InputStream / is a request sent by the client, this is the file path, i.e. "RemoteFile.txt" BufferedReader streamReader = new BufferedReader (new InputStreamReader (inputFromSocket)) ; file &: // Home / InputStream must first be converted to the BufferedReader FileReader fileReader = new FileReader (new file (streamReader.readLine ())); file &: // read from file path / BufferedReader, create a new object FileReader BufferedReader bufferedFileReader = new BufferedReader (fileReader); file &: // again / time to establish BufferedReader objects, this time it is read to obtain the contents of a file inside the PrintWriter streamWriter = new PrintWriter (OutputStream); file &: // to / Socket of outputToSocket stream packed into PrintWriter to enable us to send file information to the client string line = null; while ((line = buffredfilereader.readline ())! = Null) {streamwriter.println (line); } File &: // Read the file information from the / bufferedFileReader, then output to the client fileReader.close () via streamwriter; streamwriter.close (); // Note that the two streams of the socket is streamReader.close (); File &: // Turn off all flows after /bene (Exception E) {system.out.println ("Error Handling a client: e);}} Please pay attention to complete the order after all operations, StreamWriter Close up before the StreamReader closes. This is not accidental. If you turn it off, the client will not get any file information, you can debug a look. This is why? Cause If you close StreamReader before closing streamwriter, you can Streamwriter is written in anything, but no data can pass through the channel (the channel is turned off). But weird, I am not output in the previous streamwriter.println ()? Is it necessary to wait until all streams What can I get to the client's information? I tried to put streamwriter.close (); streamReader.close (); shielded, see if normal communication can be realized, the result is not possible, the program is dead. Maybe because the channel is not It is possible to close. So at least, only the channel is transmitted properly, the client can not be completed, otherwise the client does not accept information. Finally, it is still a summary of the steps to create a server-side program 1. You can use one you Want to listen to the port that is incoming to the client (such as 3000 in the program) to instantiate a Serversocket (e.g. Exception). 2. Circular Call ServerSocket's Accept () to listen to the connection 3. Get the client's Socket flow for read / write operation 4. Package 5. Read and write the client's socket 6. Close the open stream (remember, never be closed Writer is turned off before the Reader is completed, and the communication below is the code list of RemoteFileServer.