Basic java knowledge-network programming and IO stream

Source: Internet
Author: User
Tags object serialization

Basic java knowledge-network programming and IO stream
IO stream

Byte stream: The Stream object that processes byte data. The smallest data unit in the computer is byte. InputStream OutputStream

Character stream: The character encoding problem. Encapsulating the byte stream and the encoding table into an object is the character stream. Reader Write

IO exceptions occur in both read and write operations. Io Exception Handling Method: io must be written to finally. Fw. flush (); // refresh the buffer, fw. close (); // close the stream.

IO uses a design pattern: decorative design pattern. Decoration Design Mode solution: Enhance the functions of a group of classes. Packaging: Write a class (Packaging class) to package the packaged object. * 1. The packaging class and the encapsulated object must implement the same interface. * 2. The packaging class must hold a packaged object; * 3. When a packaging class implements an interface, most of the methods are implemented by calling the encapsulated object. we implement the methods that need to be modified by ourselves;
Stream Reader: an abstract class used to read the stream. The sub-classes must implement only read (char [], int, int) and close () methods (). Writer: the abstract class for writing streams. The sub-classes must implement only write (char [], int, int), flush (), and close () methods (). Byte stream

InputStream and OutputStream

BufferedWriter: improves the efficiency of the character output stream. This means that when a buffer object is created, a stream object must first exist. Improve the efficiency of specific stream objects. FileWriter fw = new FileWriter ("bufdemo.txt"); BufferedWriter bufw = new BufferedWriter (fw); // associate the buffer zone with the specified stream. For (int x = 0; x <4; x ++) {bufw. write (x + "abc"); bufw. newLine (); // write a line break that can be written to different platforms. Bufw. flush (); // refresh the buffer to make the data to the destination .} Bufw. close (); // close the buffer, which is actually shutting down the specific stream. Optional BufferedReader: FileReader fr = new FileReader ("bufdemo.txt"); BufferedReader bufr = new BufferedReader (fr); String line = null; while (line = bufr. readLine ())! = Null) {e // The returned result of the readLine method does not contain line breaks. System. out. println (line);} bufr. close (); --------------------------- // remember to use this sentence as soon as you read the keyboard entry. BufferedReader bufr = new BufferedReader (new InputStreamReader (System. in); BufferedWriter bufw = new BufferedWriter (new OutputStreamWriter (System. out); // output to the console String line = null; while (line = bufr. readLine ())! = Null) {if ("over ". equals (line) break; 51/65 bufw. write (line. toUpperCase (); // convert the input characters into uppercase characters and output the bufw. newLine (); bufw. flush ();} bufw. close (); bufr. close ();

Flow operation rules:

1. Clarify the source and purpose.
Data source: the data source needs to be read. Two systems can be used: InputStream and Reader;
Data collection: writing is required. Two systems can be used: OutputStream and Writer;

2. Is the operated data plain text data?
For example: Data source: Reader
Data collection: Writer
If not: Data source: InputStream
Data collection: OutputStream

3. Although a system has been identified, there are too many objects in the system. Which one is used?
Specific data devices.
Devices corresponding to the Data source: Hard Disk (File), memory (array), and keyboard (System. in)
Devices for data collection: Hard Disk (File), memory (array), and console (System. out ). 4. Do I need to add other functions to basic operations? For example, buffer.
Decoration if needed. The File class encapsulates files and folders in the File system into objects. Provides more attributes and actions for these files and folders.
. These cannot be done by the stream object, because the stream only operates on data.
CreateNewFile (), mkdir (), getAbsolutePath () Recursion

Usage: this function is used internally, but the passed parameter value is unknown.

Recursive considerations:
1: Define recursive conditions.
2: Do not use too many recursion times. It is prone to StackOverflowError stack memory overflow errors.
In fact, recursion is to constantly load the same function in the stack memory.

A small example of a Java recursive algorithm: 1 + 2 + 3... + 1000 and

Public class Test1 {int sum = 0; int a = 1; public void sum () {sum + = a; a ++; if (a <= 1000) {sum (); // call itself to implement recursion} public static void main (String [] args) {Test1 test = new Test1 (); test. sum (); System. out. println ("Calculation Result:" + test. sum + "! ");}
Extended Stream object PrintStream: Print stream PrintStream m can be operated for: 1: File object. 2: String path. 3: byte output stream. PrintWriter: the object has four destinations: 1: File object. 2: String path. 3: byte output stream. 4: character output stream. PrintWriter out = new PrintWriter (new FileWriter(“out.txt "), true); // automatically refresh System after setting true. in, System. the two standard input and output streams out already exist at jvm startup. It can be used at any time. When
The jvm is over, and the two streams are over. However, when the show close method is used to close the stream, the two streams will end early. SequenceInputStream: sequence stream

The function is to merge multiple read streams into one read stream to merge data.

Merging principle: Multiple read streams correspond to one output stream.
Cutting Principle: one read stream corresponds to multiple output streams. Pipeline Flow

The pipeline reads the stream and the pipeline writes the stream to the same connection as the pipeline, and the pipeline reads the data written by the pipeline write stream.
Note: multithreading technology should be added. Because a single thread executes read first, a deadlock will occur, because the read method is blocking and there is no data.
The read method will let the thread wait.

public static void main(String[] args) throws IOException{PipedInputStream pipin = new PipedInputStream();PipedOutputStream pipout = new PipedOutputStream();pipin.connect(pipout);new Thread(new Input(pipin)).start();new Thread(new Output(pipout)).start();}
Object serialization

Static data cannot be serialized because the static data is not in the heap memory. You can modify the variable with the transient keyword to not serialize non-static data.

Serializable: used to start the object serialization function. It can force the specified class to have the serialization function. This interface has no members. This is
Mark interfaces.

ByteArrayInputStream: Source: Memory
ByteArrayOutputStream: Objective: memory.
These two stream objects do not involve underlying resource calls. They operate on arrays in the memory, so they do not need to be closed.

Network Programming

Port: 0-65535

// Obtain an ip object by name (ip string or host name. InetAddress ip = InetAddress. getByName ("www.baidu.com"); // java.net. UnknownHostException
Socket

A mechanism provided for network services. both ends of the communication have sockets. network communication is actually the communication between sockets.
The Socket is transmitted through IO.

Udp Transmission

Data must be encapsulated into data packets, including the destination address, port, and data. It encapsulates udp into an object, which is easy to use. This object is DatagramSocket.

Sender:

1. Create a udp socket service. If no port is specified when an object is created, the system will automatically allocate an unused port.

2. Specify the specific data to be sent.

3. encapsulate data into data packets.

4. Use the send method of the socket service to send data packets.

5. Close the resource.

Import java.net. *; class UdpSend {public static void main (String [] args) throws Exception {// 1 1, establish the t socket service of p udp. DatagramSocket ds = new DatagramSocket (8888); // specify the sending port. If this parameter is not specified, the system will randomly allocate the port. // 2 2. Specify the specific data to be sent. String text = "udp transmission demonstration buddy"; byte [] buf = text. getBytes (); // 3, encapsulate the data into a data packet. DatagramPacket dp = new DatagramPacket (buf, buf. length, InetAddress. getByName ("10.1.31.127"), 10000); // 4 4, use the d send method of the t socket service to send the data packet. Ds. send (dp); // 5 5. Close the resource. Ds. close ();}}

Receiving end of p udp:
1. To create a udp socket service, you must specify a port to ensure that only the data sent to the port is available at the receiving end.
To process the data.

2. Define a data packet to store the received data.

3. Store the received data to the data packet through the Receiving Method of the socket service.

4. Obtain the specific data content in the data packet through the data packet method, such as ip address, port, and data.

5. Close the resource.

Class UdpRece {public static void main (String [] args) throws Exception {// 1, create a p udp t socket service. DatagramSocket ds = new DatagramSocket (10000); // 2 2. defines a data packet for storing received data. First, define the byte array, and the data will be stored in the byte array. Byte [] buf = new byte [1024]; DatagramPacket dp = new DatagramPacket (buf, buf. length); // 3 3, store the received data to the data packet through the Receiving Method of the t socket service. Ds. receive (dp); // This method is a blocking method. // 4 4. Obtain the specific data content in the data packet through the data packet method, such as ip address, port, and data. String ip = dp. getAddress (). getHostAddress (); int port = dp. getPort (); String text = new String (dp. getData (), 0, dp. getLength (); // convert the valid part of the byte array into a string. System. out. println (ip + ":" + port + "--" + text); // 5, close the resource. Ds. close ();}}
Tcp transmission

After the two endpoints are connected, there will be a channel for data transmission. This channel is called a stream and is a stream built on the network,
It is called a socket stream. The stream can be read or written.

TCP client:

1. Establish a tcp socket service. It is best to specify the specific address and port. When this object is created, you can
Connect (three-way handshake ).

2. If the connection is successful, it means that the channel is established and the socket stream is generated. You only need to obtain the read stream and write in the socket stream.
Stream. You only need to use getInputStream and getOutputStream to obtain two stream objects.

3. Close the resource.

Import java.net. *; import java. io. *; // requirement: the client sends data to the server. Class TcpClient {public static void main (String [] args) throws Exception {Socket s = new Socket ("10.1.31.69", 10002); OutputStream out = s. getOutputStream (); // gets the output stream object in the t socket stream. Out. write ("tcp demo, buddy again! ". GetBytes (); s. close ();}}

TCP Server:

1. Create a socket service on the server and listen to a port.

2. In order to provide services to the client, the server can obtain the client content through the accept method.

3. You can use the socket stream in the obtained socket object to communicate with a specific client.

4. If the communication ends, close the resource. Note: first shut down the client and then the server.

Class TcpServer {public static void main (String [] args) throws Exception {62/65 ServerSocket ss = new ServerSocket (10002); // establish the socket service Socket s = ss on the server. accept (); // obtain the client object String ip address = s. getInetAddress (). getHostAddress (); System. out. println (ip + "..... connected "); // you can use the socket stream in the obtained socket object to communicate with a specific client. InputStream in = s. getInputStream (); // read data from the client. Use the socket of the client object to read the stream byte [] buf = new byte [1024]; int len = in. read (buf); String text = new String (buf, 0, len); System. out. println (text); // if the communication ends, close the resource. Note: first shut down the client and then shut down the server. S. close (); ss. close ();}}
Reflection Technology

Reflection technology can dissect a class.

Basic steps:
1. Get the s Class object, which is the object of the bytecode file with the specified name.
2. instantiate the object to obtain the attributes, methods, or constructor of the class.
3. Common Operations for accessing attributes, calling methods, and calling constructors to create object Regular Expressions:
1. Matching: Actually, the matches method in the String class is used.
String reg = "[1-9] [0-9] {4, 14 }";
Boolean B = qq. matches (reg); // associate the regular expression with the string to match the string.

2. Cut: The split method in the String class is used.

3. Replace: replaceAll () in the String class ();

4. obtain:
1), first compile the regular expression into a regular object. The static method compile (regex) in Pattern is used );

2) Get the Matcher object through the Pattern object.
Pattern is used to describe a regular expression and can be parsed.
The rule operation string needs to be re-encapsulated into the Matcher object.
Then, use the Matcher object method to operate the string.
How can I obtain a matcher object?
Use the matcher method in the Pattern object. This method can be associated with strings based on regular rules. And returns the matching object.

3) use the method in the Matcher object to perform various regular operations on the string.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.