IO

What is I/O?

  • The process of data interaction inside and outside the program is called input and output.
    • Who is inside the program? memory
    • Who is outside the program?
      • Generally speaking, there are two types: local files and networks.
      • There are other cases, where you’re interacting with other programs, and the programs that you’re interacting with are also

      External, but in general, files and networks.

    • Reading data from a file or network into memory is called input; Writing from memory to a file or sending to the network is called output
  • Java I/O has only one function: data interaction with the outside world

usage

  • Use streams, such as FileInputStream/FileOutputStream
  • Characters can be read and written using readers and writers
  • Streams can also be nested outside of other streams, layer by layer
  • BufferedXXXX buffers the stream. For the input stream, it is read more each time in memory, the next time to go to the data do not need to do external interaction (that is, do not have to do IO operations); For the outgoing stream, the data is stored in memory for a long time before being written externally.

Caching can improve efficiency by reducing and external interactions

  • Close file :close()
  • Flush () to ensure that the data is actually written to the outside (read data without such concerns)
  • This is Java I/O, and the principle is that memory interacts with the outside world
  • There are a lot of classes involved in Java I/O, but you just need to pay attention to which one you use. Don’t memorize classes

The inheritance diagram of

FileOutputStream write operation

Private static void writeIO() {OutputStream OutputStream = null; try { outputStream = new FileOutputStream("text.txt"); outputStream.write('a'); outputStream.write('b'); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); }}}Copy the code

FileInputStream read operation

Private static void readIO() {InputStream InputStream = null; try{ inputStream = new FileInputStream("text.txt"); char content = (char) inputStream.read(); char content2 = (char) inputStream.read(); System.out.println(content); //a System.out.println(content2); //b } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); }}}Copy the code

InputStreamReader String read operation

Private static void stringIO() {try(InputStream InputStream = new FileInputStream("text.txt"); Reader reader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(reader)){ // FileReader reader = new FileReader("text.txt"); System.out.println(bufferedReader.readLine()); //ab } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}Copy the code

BufferedOutputStream read operation

private static void bosIO() { try( OutputStream os = new FileOutputStream("text.txt"); BufferedOutputStream bos = new BufferedOutputStream(os)){ bos.write('c'); bos.write('d'); // bos.flush(); // bos.flush(); / / or bos. Close (); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}Copy the code

File copy, InputStream read, OutputStream write

Public static void fileCopy(){try (InputStream is = new FileInputStream("text.txt"); public static void fileCopy(){try (InputStream is = new FileInputStream("text.txt"); OutputStream OS = new FileOutputStream("text_copy.txt")){// write os.write(is.read()); byte[] data = new byte[1024]; int readCount ; while ((readCount = is.read(data))! =-1){ os.write(data,0,readCount); } // InputStream is2 = new BufferedInputStream(new FileInputStream("text.txt")); // OutputStream os2 = new BufferedOutputStream(new FileOutputStream("text_copy.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}Copy the code

The client requests SocketIO

Public static void socketIO(){try {socket socket = new socket ("hencoder.com",80); public static void socketIO(){try {socket socket = new socket ("hencoder.com",80); OutputStream os = socket.getOutputStream(); InputStream is = socket.getinputStream (); BufferedWriter Writer = new BufferedWriter(new OutputStreamWriter(OS)); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); Writer. write("GET/HTTP/1.1\n"+ "Host: www.example.com\n\n"); writer.flush(); String message; while ((message = reader.readLine())! =null){ System.out.println(message); Println (reader.readline ());} system.out.println (reader.readline ()); //HTTP/1.1 200 OK} catch (IOException e) {e.printStackTrace(); }}Copy the code

The service side serverSocketIO

//serverSocket public static void serverSocketIO(){ try (ServerSocket serverSocket = new ServerSocket(100); Socket socket = serverSocket.accept(); OutputStream os = socket.getOutputStream(); InputStream is = socket.getinputStream (); BufferedWriter Writer = new BufferedWriter(new OutputStreamWriter(OS)); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); ) {writer.write("HTTP/1.1 200 OK\n" + "Date: Mon, 23 May 2005 22:38:34 GMT\n" + "Content-type: text/ HTML; charset=UTF-8\n" + "Content-Length: 138\n" + "Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT\n" + "Server: Apache/1.3.3.7 (Unix) (Red-hat /Linux)\ N "+ "ETag: \" 3f80F - 1b6-3e1CB03b \"\ N" + "Accept-ranges: bytes\n" + "Connection: close\n" + "\n" + "<html>\n" + " <head>\n" + " <title>An Example Page</title>\n" + " </head>\n" + " <body>\n" + " <p>Hello World, this is a very simple HTML document.</p>\n" + " </body>\n" + "</html>\n\n"); writer.flush(); } catch (IOException e) { e.printStackTrace(); }}Copy the code

NIO

There are several differences between NIO and IO:

  1. The traditional IO uses the way of inserting pipes, using Stream;
    • NIO also uses the way of inserting pipes, using Channel.
    • NIO channels are two-way
  2. NIO also uses buffers
    • Its buffers can be manipulated
    • It enforces the use of Buffer
    • Its buffer doesn’t work well
  3. NIO has non-blocking support
    • Only non-blocking is supported, not all non-blocking. The default is blocking
    • And even if it is non-blocking, it is only supported for network interaction, not file interaction

use

  • NIO’s Buffer model:
  • NIO to read a file
    • Get the Channel using fine.getChannel()
    • Then create a Buffer
    • Then use channel.read(buffer) to read the contents of the file
    • When you’ve finished reading, flip()
    • Start using Buffer
    • Remember to clear() after use
public class NIOMain { public static void main(String[] args) { // nio1(); //NIO nio2(); Private static void nio1() {try {RandomAccessFile file = new RandomAccessFile("text.txt","r"); private static void nio1() {try {RandomAccessFile file = new RandomAccessFile("text.txt","r"); FileChannel channel = file.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); channel.read(byteBuffer); // bytebuffer.limit (bytebuffer.position ()); // byteBuffer.position(0); byteBuffer.flip(); System.out.println(Charset.defaultCharset().decode(byteBuffer)); byteBuffer.clear(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void nio2() { try { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress(99)); / / non-blocking start - >. The following code for non-blocking configuration serverSocketChannel configureBlocking (false); // non-blocking Selector = Selector. Open (); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true){ selector.select(); / / blocked for (SelectionKey key: the selector selectedKeys ()) {SocketChannel SocketChannel = serverSocketChannel. The accept (); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); while (socketChannel.read(byteBuffer)! =-1){ byteBuffer.flip(); socketChannel.write(byteBuffer); byteBuffer.clear(); } } } } catch (IOException e) { e.printStackTrace(); }}}Copy the code

OKIO

Features:

  • It is also intubation-based and unidirectional. The input Source is called Source and the output target is called Sink
  • Support the Buffer
    • Like NIO, buffers can be manipulated
    • Buffer is not mandatory
public class OKIOMain { public static void main(String[] args) { try (BufferedSource source = Okio.buffer(Okio.source(new File("text.txt")))){ System.out.println(source.readUtf8Line()); //ab } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Try (Source Source = okio.source (new File("text.txt")) {// Buffer buffer = new buffer (); // buffer buffer = new buffer (); // source.read(buffer,1024); // System.out.println(buffer.readUtf8Line()); //ab //} catch (FileNotFoundException e) { // e.printStackTrace(); //} catch (IOException e) { // e.printStackTrace(); / /}}}Copy the code