Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of java IO?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the knowledge points of java IO". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. Overview

Java's iPot O can be roughly divided into the following categories:

Disk operation: File

Byte operations: InputStream and OutputStream

Character operations: Reader and Writer

Object manipulation: Serializable

Network operation: Socket

New input / output: NIO

II. Disk operation

The File class can be used to represent information about files and directories, but it does not represent the contents of the file.

Recursively list all files in a directory:

Public static void listAllFiles (File dir) {if (dir = = null | |! dir.exists ()) {return;} if (dir.isFile ()) {System.out.println (dir.getName ()); return;} for (File file: dir.listFiles ()) {listAllFiles (file);}}

Starting with Java7, you can use Paths and Files instead of File.

3. Public static void copyFile (String src, String dist) throws IOException {FileInputStream in = new FileInputStream (src); FileOutputStream out = new FileOutputStream (dist); byte [] buffer = new byte [20 * 1024]; int cnt / / read () reads a maximum of buffer.length bytes / / returns the actual number of bytes read / / returns-1 indicates that the eof has been read, that is, the tail while ((cnt = in.read (buffer, 0, buffer.length)! =-1) {out.write (buffer, 0, cnt);} in.close (); out.close ();} decorator mode

Java I PUBO is implemented using the decorator pattern. Take InputStream as an example

InputStream is an abstract component

FileInputStream is a subclass of InputStream and belongs to concrete components. It provides input operation of byte stream.

FilterInputStream is an abstract decorator, which is used to decorate components and provide additional functionality for components. For example, BufferedInputStream provides caching for FileInputStream.

When you instantiate a byte stream object with caching function, you only need to set another layer of BufferedInputStream object on the FileInputStream object.

FileInputStream fileInputStream = new FileInputStream (filePath); BufferedInputStream bufferedInputStream = new BufferedInputStream (fileInputStream)

The DataInputStream decorator provides operations for entering more data types, such as int, double, and other basic types.

IV. Coding and decoding of character operations

Encoding is converting characters into bytes, while decoding is reassembling bytes into characters.

If the encoding and decoding processes use different encoding methods, then garbled code occurs.

In GBK coding, Chinese characters account for 2 bytes and English characters account for 1 byte.

In UTF-8 coding, Chinese characters account for 3 bytes and English characters account for 1 byte.

In UTF-16be coding, both Chinese and English characters account for 2 bytes.

The be in UTF-16be refers to Big Endian, that is, the big end. Accordingly, UTF-16le,le refers to Little Endian, that is, small end.

Java's memory encoding uses double-byte encoding UTF-16be, which does not mean that Java supports only this encoding, but that the type char uses UTF-16be for encoding. The char type is 16 bits, that is, two bytes, and Java uses this double-byte encoding so that both Chinese and English can be stored in an char.

The coding mode of String

String can be regarded as a character sequence, you can specify an encoding method to encode it into a byte sequence, or you can specify an encoding method to decode a byte sequence into String.

String str1 = "Chinese"; byte [] bytes = str1.getBytes ("UTF-8"); String str2 = new String (bytes, "UTF-8"); System.out.println (str2)

When calling the parameterless getBytes () method, the default encoding is not UTF-16be. The advantage of double-byte encoding is that you can use one char to store Chinese and English, which is no longer needed to convert String to an bytes [] byte array, so double-byte encoding is no longer needed. The default encoding of getBytes () is platform-dependent and is generally UTF-8.

Byte [] bytes = str1.getBytes (); Reader and Writer

Whether it is a disk or a network transfer, the smallest storage unit is bytes, not characters. However, the data operated in the program is usually in the form of characters, so it is necessary to provide a method to manipulate the characters.

InputStreamReader implements decoding from byte stream to character stream

OutputStreamWriter encodes character streams into byte streams.

Implement public static void readFileContent (String filePath) throws IOException {FileReader fileReader = new FileReader (filePath); BufferedReader bufferedReader = new BufferedReader (fileReader); String line;while ((line = bufferedReader.readLine ())! = null) {System.out.println (line) to output the text file line by line } / / the decorator pattern makes BufferedReader combine a Reader object / / when calling the close () method of BufferedReader, the close () method of Reader is called / / so only a close () call can bufferedReader.close (). Fifth, serialization of object operations.

Serialization is to convert an object into a sequence of bytes for easy storage and transmission.

Serialization: ObjectOutputStream.writeObject ()

Deserialization: ObjectInputStream.readObject ()

Static variables are not serialized because serialization only holds the state of the object, and static variables belong to the state of the class.

Serializable

The serialized class needs to implement the Serializable interface, which is just a standard, and there are no methods to implement, but if serialized without implementing it, an exception is thrown.

Public static void main (String [] args) throws IOException, ClassNotFoundException {AA1 = new A (123, "abc"); String objectFile = "file/a1"; ObjectOutputStream objectOutputStream = new ObjectOutputStream (new FileOutputStream (objectFile)); objectOutputStream.writeObject (A1); objectOutputStream.close (); ObjectInputStream objectInputStream = new ObjectInputStream (new FileInputStream (objectFile)); Aa2 = (A) objectInputStream.readObject (); objectInputStream.close (); System.out.println (a2);} private static class An implements Serializable {private int XTX private String y A (int x, String y) {this.x = x position this.y = y;} @ Overridepublic String toString () {return "x =" + x + "+" y = "+ y;}} transient

The transient keyword can prevent some properties from being serialized.

The array elementData that stores data in ArrayList is decorated with transient because the array is dynamically extended and not all space is used, so everything does not need to be serialized. By overriding serialization and deserialization methods, it is possible to serialize only that part of the data that has content in the array.

Private transient Object [] elementData; VI. Network operation

Network support in Java:

InetAddress: used to represent hardware resources on the network, that is, IP addresses

URL: uniform resource locator

Sockets: using TCP protocol to realize network communication

Datagram: uses the UDP protocol to achieve network communication.

InetAddress

There is no public constructor, and instances can only be created through static methods.

InetAddress.getByName (String host); InetAddress.getByAddress (byte [] address); URL

Byte stream data can be read directly from URL.

Public static void main (String [] args) throws IOException {URL url = new URL ("http://www.baidu.com");/* byte stream * / InputStream is = url.openStream (); / * character stream * / InputStreamReader isr = new InputStreamReader (is," utf-8 "); / * provide caching function * / BufferedReader br = new BufferedReader (isr); String line While ((line = br.readLine ())! = null) {System.out.println (line);} br.close ();} Sockets

ServerSocket: server-side class

Socket: client class

The server and client input and output through InputStream and OutputStream.

Datagram

DatagramSocket: communication class

DatagramPacket: packet class

7. NIO

The new input / output (NIO) library is introduced in JDK 1.4, which makes up for the deficiency of the original I / O and provides a high-speed, block-oriented I / O.

Flow and block

The most important difference between NIO and iCandle O is the way in which data is packaged and transmitted, in which data is processed by stream while NIO is processed in blocks.

Stream-oriented IWeiO processes one byte of data at a time: one input stream generates one byte of data, and one output stream consumes one byte of data. It is easy to create filters for streaming data, and several filters are linked so that each filter is responsible for only part of the complex processing mechanism. The downside is that stream-oriented I _ map O is usually quite slow.

Block-oriented IWeiO processes one block at a time, and it is much faster to process data by block than by stream. However, the block-oriented Iamp O lacks some of the elegance and simplicity of the stream-oriented Imax O.

The java.io.* O package has been well integrated with NIO, and java.io.* has been reimplemented on the basis of NIO, so now it can take advantage of some of the features of NIO. For example, some classes in the java.io.* package contain methods for reading and writing data in blocks, which makes processing faster even in stream-oriented systems.

Channel and buffer 1. Aisle

The channel Channel is a simulation of the stream in the original Iamp O packet through which data can be read and written.

Channels differ from streams in that a stream can only move in one direction (a stream must be a subclass of InputStream or OutputStream), while channels are bi-directional and can be used for reading, writing, or both.

Channels include the following types:

FileChannel: reading and writing data from a file

DatagramChannel: read and write data in the network through UDP

SocketChannel: read and write data in the network through TCP

ServerSocketChannel: you can listen for incoming TCP connections and create a SocketChannel for each incoming connection.

two。 Buffer zone

All data sent to a channel must first be put into the buffer, and similarly, any data read from the channel must be read into the buffer first. In other words, the data will not be read or written to the channel directly, but will be passed through the buffer first.

A buffer is essentially an array, but it is not just an array. Buffers provide structured access to data and track the read / write process of the system.

Buffers include the following types:

ByteBuffer

CharBuffer

ShortBuffer

IntBuffer

LongBuffer

FloatBuffer

DoubleBuffer

Buffer state variable

Capacity: maximum capacity

Position: the number of bytes currently read and written

Limit: the number of bytes that can also be read and written.

Examples of the process of changing state variables:

① creates a new buffer of 8 bytes, where position is 0 and limit = capacity = 8. The capacity variable does not change, and the following discussion ignores it.

② reads 5 bytes of data from the input channel and writes it to the buffer. When position is 5, the limit remains the same.

Before ③ can write the data from the buffer to the output channel, it needs to call the flip () method, which sets limit to the current position and position to 0.

④ fetches 4 bytes from the buffer into the output buffer, where position is set to 4.

⑤ finally needs to call the clear () method to clear the buffer, where both position and limit are set to the original location.

File NIO instance

The following shows an example of using NIO to quickly copy files:

Public static void fastCopy (String src, String dist) throws IOException {/ * get the input byte stream of the source file * / FileInputStream fin = new FileInputStream (src); / * get the file channel of the input byte stream * / FileChannel fcin = fin.getChannel (); / * get the output byte stream of the target file * / FileOutputStream fout = new FileOutputStream (dist); / * get the file channel of the output byte stream * / FileChannel fcout = fout.getChannel () / * allocate 1024 bytes to the buffer * / ByteBuffer buffer = ByteBuffer.allocateDirect (1024); while (true) {/ * read data from the input channel into the buffer * / int r = fcin.read (buffer); / * read () return-1 indicates EOF * / if (r =-1) {break;} / * switch read / write * / buffer.flip () / * write the contents of the buffer to the output file * / fcout.write (buffer); / * clear the buffer * / buffer.clear ();}} selector

NIO is often called non-blocking IO, mainly because the non-blocking feature of NIO in network communication is widely used.

NIO implements the Reactor model in IO multiplexing. A thread Thread uses a selector Selector to listen for events on multiple channels Channel by polling, so that a thread can handle multiple events.

By configuring the listening channel Channel to be non-blocking, when the IO event on the Channel has not yet arrived, it will not enter the blocking state and wait for it. Instead, it will continue to poll other Channel to find the Channel execution where the IO event has arrived.

Because of the high overhead of creating and switching threads, using one thread to handle multiple events instead of one thread has good performance for IO-intensive applications.

It should be noted that only socket Channel can be configured as non-blocking, while FileChannel cannot, and it doesn't make sense to configure non-blocking for FileChannel.

1. Create the selector Selector selector = Selector.open (); 2. Register the channel on the selector ServerSocketChannel ssChannel = ServerSocketChannel.open (); ssChannel.configureBlocking (false); ssChannel.register (selector, SelectionKey.OP_ACCEPT)

The channel must be configured in non-blocking mode, otherwise there is no point in using selectors, because if the channel is blocked on one event, the server cannot respond to other events and must wait for this event to be processed before it can handle other events, which obviously runs counter to the role of selectors.

When registering a channel with a selector, you also need to specify specific events to register, mainly in the following categories:

SelectionKey.OP_CONNECT

SelectionKey.OP_ACCEPT

SelectionKey.OP_READ

SelectionKey.OP_WRITE

They are defined in SelectionKey as follows:

Public static final int OP_READ = 1

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report