Java IO stream summary

In the previous words: IO stream is used to operate File, so let's talk about File first

First, the File class: abstract representation of file and directory path names.

The File class can only manipulate the attributes of the file, but the contents of the file cannot be manipulated.

1. Function: used to operate on disk files. delete, create, etc.

2. Three constructors:

① Directly pass in a path to get a file or folder

File file1 = new File("F:\\test");

②The first parameter is passed in the parent path, and the second parameter is passed in the child path or file

File file2 = new File("F:\\test", "test.txt");

③ The first parameter is passed in the file file, and the second parameter is passed in the sub-path or file

File file3 = new File(file1, "test.txt");

3. The representation of the path:

Folder division can use "/", usually used in Linux system, windows can also be used

"\\" is usually used in Windows systems, note that '\' needs to be escaped

4. Several common methods that need attention

①: .delete() delete file delete successfully true, delete failed false; if a folder is deleted, this folder cannot have sub-content

②: createNewFile() creates a new file and returns false if the creation fails. The new file name that needs to be specified is determined by the file object that calls him, instead of passing parameters. If it is not created successfully, an exception needs to be caught.

③: mkdir: Only one layer of directories can be created. If the penultimate layer of directories does not exist, the creation fails; mkdirs: Multi-layer directories can be created, and they can be created in sequence no matter how many layers do not exist.

④: list() returns the names of all files and folders in the current directory, and the return value type is String[]

String[] list = file1.list();
for (String string : list) {
    System.out.println(string);
}

The implementation class object of the FilenameFilter interface can be passed in the parameter, indicating that the accept method needs to be rewritten to traverse and filter all the files in the list.
If the current file is retained, return true, and if the current file is not required, return false

String[] list1 = file1.list(new FilenameFilter()) {
    @Override
    public boolean accept(File dir, String name) {
    // dir: indicates the parent path containing the current folder
    // name: indicates the current file name 
          if (name.endsWith( " .txt " )) {
               return  true ;
          }else {
              return false;
          }
    }
});
for (String string1 : list1) {
    System.out.println(string1);
}            

⑤: Returns the paths of all files and folders in the current directory, the return value type is File[]

File[] files = file1.listFiles();
for (File file : files) {
    System.out.println(file+"----"+file.getName());
}

You can also filter files
①Use FilenameFilter() to filter like list()
②Use the implementation class of the FileFilter interface to filter

File[] files1 = file1.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
        // TODO Auto-generated method stub
                if (pathname.getName().endsWith(".txt")) {
            return true;
          }else {
            return false;
          }
    }
});
for (File fileN: files1) {
    System.out.println(fileN+"----"+fileN.getName());
}    

 

Second, the classification of IO streams:

1. According to the direction of the flow: input flow and output flow

2. According to the size of the read text: byte stream and character stream (byte stream is read according to bytes, which is easy to garbled when reading Chinese; character stream is read according to characters, which is usually used to read Chinese

3. According to the way of reading: node stream and cache stream

Three, byte stream java.io.InputStream java, io, OutputStream

1. FileInputStream class

① This stream inherits from InputStream and is used to read data from a file, and its object can be created with the keyword new.
②The construction method
can use the file name of string type to create an input stream object to read the file:
FileInputStream f = new FileInputStream("C:/java/hello");
You can also use a file object to create an input stream object to read the file. We first have to use the File() method to create a file object:
File f = new File("C:/java/hello");
FileInputStream out = new FileInputStream(f);
③ Common method
available(): return the next pair The number of bytes that methods called by this input stream can read from this input stream without blocking. Returns an integer value.
read(int r): This method reads the specified bytes of data from the InputStream object. Returned as an integer value. Returns the next byte of data, or -1 if the end has been reached.
read(byte[] b): Read up to b.length bytes of data from this input stream into a byte array
close(): Close this file input stream and release all system resources associated with this stream. Throws IOException

2.FileOutStream

① This class is used to create a file and write data to the file.
If the destination file does not exist before the stream opens the file for output, the stream creates the file.
②The construction method
uses the file name of string type to create an output stream object:
OutputStream f = new FileOutputStream("C:/java/hello");
you can also use a file object to create an output stream to write files. We first have to use the File() method to create a file object:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
③ Common method
write(int b): Specify the Bytes are written to this file output stream.
write(byte[] b): Writes b.length bytes from the specified byte array to this file output stream.

3、BufferedInputStream、BufferedOutputStream

Inherited from FilterInputStream, FilterOutputStream

1. Function: Packing on the basis of the basic stream, when reading or writing a file, it will be done through the cache.
That is, writing the content to the buffer area first, and then performing the read or write operation after the buffer area is full can greatly reduce the number of operations on
the file and improve the writing efficiency
.
Packaging:
new BufferedInputStream(new FileInputStream("F:\\test\\test.txt"));
This writing method is called IO chain. When IO is closed, the outermost stream needs to be closed, and the inner stream will be automatically closed3
. Using BufferedOutStream, the flush() method is usually called when closing;
it means that the buffer area is flushed before closing, and the remaining content of the buffer area is written to the file;
in fact, the close() method has its own refresh, which is a habit.

4.DataInputStream和DataOutputStream

1. Inherited from FilterInputStream and FilterOutStream respectively
2. Special:
①Use binary to read and write files
②Compared with basic streams, it can directly read and write basic data types in Java

3. In addition, if a file to be operated is a binary file, you need to use DataInputStream instead of FileInputStream
to read it.) Similarly, the data series stream also has read and write methods that are the same as the basic stream operations

. 4. The file written by the Data stream, Can only be read with Data stream, not with elementary stream

5. Compared with elementary streams, several unique methods
readUTF(): first read two bytes and return this string in the form of String
readInt(): read four input bytes and return an int value
readDouble() : Reads eight input bytes and returns a double value.
6. In the above method, if the stream reaches the end before reading all bytes, a
java.io.EOFException will be thrown; EOF:END OF FILE
https://www.cnblogs.com/yiwangzhibujian/p/7107084 .html (explains in detail why the exception is thrown)

The solution I figured out:

public class Demo04_DataINOUTStream2 {
    public static void main(String[] args) {
        DataInputStream dis = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("F:\\test\\Demo02_IO.class");
            if (fis.available() != 0) {
                dis = new DataInputStream(fis);
            }else {System.out 
                .println ( "The file has no more readable content! " );
            }
        try {
            while (true) {
                    System.out.println(dis.readInt());
            }} catch (EOFException e) {System.out 
                .println ( " This exception will definitely be thrown, indicating that the target file has been read, and there is no more content to read, we just don't do anything! " );
            }
        
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                dis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}


第一篇:
https://www.cnblogs.com/ouhaitao/p/7683568.html

 1      ObjectInputStream ois = null ;
  2      FileInputStream fis= new FileInputStream(filePath);
  3      // When there is content in the file 
 4      if (fis.available()!= 0 )
  5          ois = new ObjectInputStream(fis);
  6      else {
  7 System.out          .println ( "The file is empty! " );
  8          return ;
  9      }
 10      try {
 11          while ( true)                            
12           System.out.println((Student)ois.readObject());
13     }catch(EOFException e){
14     }

The principle is: first use the basic stream to judge whether the file still has readable content, and only instantiate an
advanced stream object when it is judged that there is readable content. Catch the EOFException in the read...() method and leave it alone.

The second article:
https://blog.csdn.net/ouyang_peng/article/details/46448877

5.ObjectInputStream/ObjectOutputStream

1. Inherit java.io.InputStream and java.io.OutputStream
2. The same as the basic stream, you can use the read write method directly
3. You can use the method of the Data stream
4. Special methods: readObject() and writeObject()
Sequence of objects Serialization and deserialization
1. Object serialization: the process of persistently saving objects in the program in a file ObjectOutStream
2. Object deserialization: re-reading the objects saved in the file into the program Process. If ObjectInputStream
wants to serialize the entity class object, the entity class needs to implement the Serializable (serializable) interface, and
add a serialization version number private static final long serialVersionUID = 4992258028211704199L;
if the serialization version number is not added, when serializing a After the object, if the entity class attribute is added or deleted, it will cause an error java.io.InvalidClassException when deserializing
, because the system thinks that this is not the same class.

Note that although it is called object serialization, use readObject() and writeObject () These two methods can directly pass in a collection of objects

The readObject() and writeObject() methods also have EOFException, the solution is the same
as readInt() in DataInputStream and DataOutputStream
http://note.youdao.com/noteshare?id=506c27323c6b8a0b6cf3d1f7f97639eb&sub=C87F25CC0E7342558556C89380D7E2AF

4. Character stream

1.Reader、Writer

1. When processing data units, a character is used as a unit, and a byte stream is a byte as a unit
. 2. The base classes of characters: Reader, Writer (abstract class)
FileReader, FileWrite are two types of abstract classes directly inherited. 3, FileReader, FileWrite can only use the system default encoding
format when reading and writing files; the encoding
cannot be specified. If the file format is inconsistent with the system default format, using these two methods to read and write will cause Chinese garbled
characters4 .Although it is not a cache stream, but not flush() will cause it to not be written and read.

2.InputStreamReader、OutputStreamWriter

1. Convert byte stream to character stream, and support custom encoding format for reading and writing
2. Common encoding format
ASCLL: American Standard Message Code;
ISO8859-1: Western European Code;
ANSI encoding, which can be divided into many types:
Simplified Chinese: GB2312, GBK
Traditional Chinese: big-
5 Japanese ...
Unicode encoding: international standard code, compatible with most countries The encoding formats
can be divided into: UTF-6, UTF-8, UTF-16

The following two lines decompose a string in utf-8 format into a character array b, and then use new String(b, "GBK") to generate a new GBK format string s1
String s = "China fdhasfdj";
byte [] b = s.getBytes("UTF-8");
String s1 = new String(b,"GBK");

3.BufferedReader、BufferedWriter

BufferedWriter and BufferedReader are character output and input streams with default buffering, which are more efficient than those without buffers because there are buffers.

1. BufferedWriter class
constructor: bufferedWriter bf = new bufferedWriter(Writer out );

Main method: void write(char ch);//Write a single character.

void write(char []cbuf,int off,int len)//Write a part of character data.

void write(String s,int off,int len)//Write a part of the string.

void newLine()//Write a line separator.

void flush();//Flush the buffer in the stream. Write the buffered data to the destination file.

void close();//Close this stream, it will be refreshed before closing.

2. BufferedReader class.
Constructor: BufferedReader br = new BufferReader(Reader in);

Main method: int read();//Read a single character.

int read(char[] cbuf,int off,int len);//Read characters into a part of the array. Returns the number of characters read. When the tail is reached, return -1.

String readLine(); //Read a text line.

void close(); //Close the stream. and release all resources associated with that stream.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324727526&siteId=291194637