Summary of Java IO Stream Learning VIII: Commons IO 2.5-IOUtils

Keywords: encoding Java Apache socket

Summary of Java IO Stream Learning VIII: Commons IO 2.5-IOUtils

For reprinting, please indicate the source: http://blog.csdn.net/zhaoyanjun6/article/details/55051917
This article is from [Zhao Yanjun's blog]

In the last article, I introduced the common usage of IO FileUtils, and today I introduce the use of IO Utils.

Relevant Methods of IOUtils Flow Operation

  • Copy: This method copies streams, which is the most frequently used method in this tool class. Support multiple data copies. The internal use of copy is actually the copyLarge method. Because copy can copy the byte data of Integer.MAX_VALUE, that is, 2 ^ 31-1.
copy(inputstream,outputstream)
copy(inputstream,writer)
copy(inputstream,writer,encoding)
copy(reader,outputstream)
copy(reader,writer)
copy(reader,writer,encoding)
  • CopLarge: This method is suitable for copying large data streams, such as over 2G.
copyLarge(reader,writer) By default 1024 will be used*4 OfbufferTo read
copyLarge(reader,writer,buffer)
  • Get the input stream
//Encoding formats can be specified by capturing input streams from text
InputStream toInputStream(final String input, final Charset encoding)

InputStream toInputStream(final String input, final String encoding)

//Get a buffer input stream, default buffer size 1KB
InputStream toBufferedInputStream(final InputStream input)  

//Gets an input stream of a specified buffer stream size
InputStream toBufferedInputStream(final InputStream input, int size)

//Put the entire content of the stream in another stream
BufferedReader toBufferedReader(final Reader reader)

//Put the entire content of the stream in another stream
BufferedReader toBufferedReader(final Reader reader, int size)
  • Get the content in the input stream
// Input stream - "string"
String toString(final InputStream input, final Charset encoding)

// Input stream - "string"
String toString(final InputStream input, final String encoding)

// Character Input Stream - "String"
String toString(final Reader input)

// Character Array - "String"
String toString(final byte[] input, final String encoding)

//Input Stream - "Character Array"
byte[] toByteArray(final InputStream input)

//Input Stream - "Character Array"
byte[] toByteArray(final Reader input, final Charset encoding)

//Input Stream - "Character Array"
byte[] toByteArray(final Reader input, final String encoding) 

//URL--"Character Array
byte[] toByteArray(final URI uri)

// URL - "String"
String toString(final URL url, final Charset encoding)

// URL - "String"
String toString(final URL url, final String encoding)

// URLConnection - "String
byte[] toByteArray(final URLConnection urlConn)
  • String Read-Write
List<String> readLines(InputStream input) 

List<String> readLines(InputStream input, final Charset encoding) 

List<String> readLines(InputStream input, final String encoding)

List<String> readLines(Reader input)

void writeLines(Collection<?> lines, String lineEnding, OutputStream output)

void writeLines(Collection<?> lines, String lineEnding, OutputStream output, Charset encoding)

void writeLines(Collection<?> lines, String lineEnding, OutputStream output, final encoding)

void writeLines(Collection<?> lines, String lineEnding,Writer writer)

Small example:

public void readLinesTest(){
       try{
           InputStream is = new FileInputStream("D://test1.txt");
           List<String> lines = IOUtils.readLines(is);
           for(String line : lines){
               System.out.println(line);
           }
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

Result:

hello
world
  • write: This method writes data to the output stream
write(byte[] data, OutputStream output)
write(byte[] data, Writer output)
write(byte[] data, Writer output, Charset encoding)
write(byte[] data, Writer output, String encoding)

write(char[] data, OutputStream output)
write(char[] data, OutputStream output, Charset encoding)
write(char[] data, OutputStream output, String encoding)
write(char[] data, Writer output)

write(CharSequence data, OutputStream output)
write(CharSequence data, OutputStream output, Charset encoding)
write(CharSequence data, OutputStream output, String encoding)
write(CharSequence data, Writer output)

write(StringBuffer data, OutputStream output)
write(StringBuffer data, OutputStream output, String encoding)
write(StringBuffer data, Writer output)

write(String data, OutputStream output)
write(String data, OutputStream output, Charset encoding)
write(String data, OutputStream output, String encoding)
write(String data, Writer output)
  • read: read content from a stream
read(inputstream,byte[])
read(inputstream,byte[],offset,length) 
//Offset is the offset of buffer and length is the length of read

read(reader,char[])
read(reader,char[],offset,length)

The following example:

public void readTest(){
      try{
          byte[] bytes = new byte[4];
          InputStream is = IOUtils.toInputStream("hello world");
          IOUtils.read(is, bytes);
          System.out.println(new String(bytes));

          bytes = new byte[10];
          is = IOUtils.toInputStream("hello world");
          IOUtils.read(is, bytes, 2, 4);
          System.out.println(new String(bytes));
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  • readFully: This method reads a stream of specified length and throws an exception if the read length is insufficient.
readFully(inputstream,byte[])
readFully(inputstream,byte[],offset,length)
readFully(reader,charp[])
readFully(reader,char[],offset,length)

Small example:

public void readFullyTest(){
      byte[] bytes = new byte[4];
      InputStream is  = IOUtils.toInputStream("hello world");
      try {
          IOUtils.readFully(is,bytes);
          System.out.println(new String(bytes));
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

Output: hell
Anomalies were reported:

java.io.EOFException: Length to read: 20 actual: 11
    at org.apache.commons.io.IOUtils.readFully(IOUtils.java:2539)
    at org.apache.commons.io.IOUtils.readFully(IOUtils.java:2558)
    at test.java.IOUtilsTest.readFullyTest(IOUtilsTest.java:22)
    ...
  • contentEquals: Compare two streams to see if they are equal
contentEquals(InputStream input1, InputStream input2)
contentEquals(Reader input1, Reader input2)
  • contentEqualsIgnoreEOL: Compare two streams and ignore newline characters
contentEqualsIgnoreEOL(Reader input1, Reader input2)
  • Skip: This method is used to skip a stream of specified length
long skip(inputstream,skip_length)
long skip(ReadableByteChannel,skip_length)
long skip(reader,skip_length)
  • SkpFully: This method is similar to skip, except that if the neglected length is longer than the existing length, an exception will be thrown.
skipFully(inputstream,toSkip)
skipFully(readableByteChannel,toSkip)
skipFully(inputstream,toSkip)

Small example:

public void skipFullyTest(){
    InputStream is = IOUtils.toInputStream("hello world");
    try {
        IOUtils.skipFully(is,30);
        System.out.println(IOUtils.toString(is,"utf-8"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • ineIterator: Read the stream and return to the iterator
LineIterator lineIterator(InputStream input, Charset encoding)
LineIterator lineIterator(InputStream input, String encoding)
LineIterator lineIterator(Reader reader)
  • close: close the flow
//Close URLConnection 
void close(final URLConnection conn)

//closeQuietly ignores nulls and exceptions and closes a stream
void closeQuietly(final Reader input)

void closeQuietly(final Writer output)

void closeQuietly(final InputStream input)

void closeQuietly(final OutputStream output)

void closeQuietly(final Socket sock)

void closeQuietly(final ServerSocket sock)
  • Small example 1
package com.app;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

public class A8 {

    public static void main(String[] args) {

        String meString = "Ha ha ha ha, it's off duty. hello" ;

        try {

            InputStream inputStream = IOUtils.toInputStream( meString, "utf-8" ) ;
            String mes = IOUtils.toString( inputStream , "utf-8" ) ;
            System.out.println( mes );

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Effect:

Ha ha ha ha, it's off duty, hello
  • Example 2: Simulated http requests
package com.app;
import java.io.IOException;
import java.net.URL;

import org.apache.commons.io.IOUtils;

public class A8 {

    public static void main(String[] args) {

        String meString = "http://www.baidu.com" ;

        try {
            //Simulated http requests
            String mes = IOUtils.toString( new URL( meString ) , "utf-8") ;
            System.out.println( mes );

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Operation results:

Personal micro-signal: Zhaoyan jun125, welcome attention

Posted by s2r on Wed, 09 Jan 2019 15:51:10 -0800