“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

One, the operation of the file

1. The File class (java.io.File) can represent files or directories (in Java, files and directories belong to this class, and the distinction is not very obvious).

The method under File performs disk operations on files on disk, but cannot read the contents of the files.

Note: Creating a file object and creating a file are two different concepts in JAVA. The former creates a file in the virtual machine, but does not actually create it into the OS’s file system. When the virtual machine is shut down, the created object disappears. Creating a file is actually creating a file in the system.

For example, File f=new File(” 11.txt “); // Create a file object named 11.txt

f.CreateNewFile(); // Actually create the file

2. File method

Boolean createNewFile() // Create a file Boolean mkdir() // Create a directory Boolean mkdirs() // Create multiple directories Boolean delete() // Delete files Boolean deleteOnExit(); // Delete files when the process exits. This operation is usually used to delete temporary files.Copy the code

String[] List() : Returns all File and directory names (relative paths) in the current File object.

File[] ListFiles() : Returns the current File object. All Files objects can be queried with getName().

IsDirectory () and isFile() to determine whether it is a directory or file.

String getParent() gets the file name of the parent class

File getParentFile()…

String getPath()… The path

Exists () Checks whether a file exists

Second, dealing with cross-platform

For the command: File f2=new File (” d: ABC \789\1.txt “)

This command is not cross-platform because file system separators vary from OS to OS.

Use the separtor property of the File class to return the current platform file separator.

File newD = new File("aa"+File.separator+"bb"+File.separator+"cc");

       File newF = new File(newD,"mudi.txt");

       try{

       newD.mkdirs();

       newF.createNewFile();

       }catch(Exception e){}
Copy the code

Object serialization interface

The Serializable interface has no methods and is an identity interface.

Serialization steps:

1) Implement Serializable interface

2) Instantiate object file output object

3) Output the object to a file

4) Some temporary variables do not need to exceed the lifetime of the virtual machine, need to add: TRANSIENT keyword, this attribute is not serialized.

An object that serializes its internal properties also needs a serialization interface.

I/O flow base

Input/Output: Data is exchanged across the JVM boundary with the outside world.

Note: Input/output is specific to the JVM.

5. Classification of streams

1) From the data type: byte stream and character stream

Byte stream class:

Abstract parent classes: InputStream,OutputStream

Implementation class:

BufferedInputStream Buffered stream – Overstream

                            BufferedOutputStream

ByteArrayInputStream Byte array stream – node stream

                            ByteArrayOutputStream

DataInputStream handles the JAVA standard data stream – the overstream

                            DataOutputStream

FileInputStream handles file IO streams – node streams

                            FileOutputStream

FilterInputStream implements the stream – byte stream parent class

                            FilterOutputStream

PipedInputStream pipe flow

                            PipedOutputStream

PrintStream contains print() and println()

RandomAccessFile supports random files

Abstract parent classes: Reader, Writer

Implementation class:

                            BufferedReader

                            BufferedWriter

                            PrintWriter

                            CharArrayReader

                            CharArrayWriter

                            FileReader

                            FileWriter

                            FilterReader

                            FilterWriter

                            InputStreamReader

                            OutputStreamWriter

                            PipedReader

                            PipedWriter

                            StringReader

                            StringWriter

  1. From the data direction: input stream and output stream

                            InputXXXXX  ,  OutputXXXXX

  1. Functions from flow: nodal flow and filter flow (used to painter mode)

Node streams are used to transfer data.

Filter streams are used to encapsulate node streams or other filter streams, thereby adding functionality to node streams or other filter streams.

I/O input and output

The standard way to write a stream is:

OutputStream os=null; OutputStream os=null; try{ String a="hello"; byte[] b=a.getBytes(); os=new FileOutputStream("D:\aa.txt"); os.write(b); }catch(IOException ioe){ ioe.printStackTrace(); }finally{ if(os! =null){ try { os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}}Copy the code

  1. InputStream class

All the parent class in the input stream of bytes, such as: FileInputStream, ObjectInputStream, PipedInputStrean

  1. Three basic read() methods

A. int read(): a byte or -1 read from the stream; (Actually read how long)

B. int read(byte[]) : reads data into an array of bytes and returns the number of bytes read; (Expect to read how long)

C. Int read(byte[], int, int) : The two int arguments specify the subrange of the array to be filled.

  1. Other methods

A. void close(): Close the stream. If a filter stream is used, closing the stream at the top of the stack will close the rest of the stream.

B. Int available(): Returns the number of bytes that can be read from the stream.

C. Skip (long): Discard the specified characters in the stream.

      d. boolean markSupported()

      e. void mark(int)

      f. void rese()

  1. OutputStream method

Answer: 1) The three basic read() methods

      a. void write():

B. void write (byte []) :

C. Void write(byte[], int, int) :

Write the output stream.

2) Other methods

A. void close(): Close the stream. If a filter stream is used, closing the stream at the top of the stack will close the rest of the stream.

B. void flush(): allows you to force write operations.

Note: The close() method is controlled by the programmer in the flow. Because the input and output streams are beyond the boundaries of the JVM, it may sometimes be impossible to reclaim resources.

Rule: Any resources that cross the boundaries of the virtual machine should be closed by the programmer, not garbage collected.

  1. FileInputStream and FileOutputStream

A: 1) Node streams, using disk files.

2) To construct a FileInputStream, the associated file must exist and be readable.

3) To construct a FileOutputStream if the output file already exists, it will be overwritten.

FileInputStream infile = new FileInputStream("myfile.dat"); FIleOutputStream outfile = new FileOutputStream("results.dat"); FileOutputStream outfile = new FileOutputStream(" results.dat ",true);Copy the code

The output is add when the argument is true, and overwrite when the argument is false.

FileOutputStream class code:

Public FileOutputStream(String name){ This(name! = null? new File(String):null,false); }Copy the code

Keyboard flow

         PrintWriter : System.in

4. A DataInputStream and DataOutputStream

Is the filter flow. To read and write Java base classes through streams, note that the DataInputStream and DataOutputStream methods are paired.

Filtering flow. Output input various data types.

WriteBoolean (Boolean b) —— send 1bit data

WriteByte (int) —— Send 1 byte data

WriteBytes (String s) ——– Send data in byte sequence

WriteChar (int v) — in 2 bytes

WriteChars (String s)————- in 2 byte sequence

WriteDouble (double D) ——- in 8 bytes

         writeInt(int v)

         writeLong(long l)

         writeShort(short s)

WriteUTF (String)———– can output Chinese!

6. ObjectInputStream and ObjectOutputStream

Filtering flow. Handles persistence of objects

Object o = new Object(); FileOutputStream fos=new FileOutputStream("Object.txt"); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(o); oos.close(); FileInputStream fis = new FileInputStream (" Object. TXT "); ObjectInputStream ois =new ObjectInputStream(fis); Object o = (Object)Ois.readObject(); ois.close();Copy the code

  1. BufferInputStream and BufferOutputStream

Filtering flows improves I/O operation efficiency

Used to add a buffer to the node stream.

A buffer is created inside the VM. Data is written to the buffer first and written out once the buffer is full, which is very efficient.

The speed of using buffered input/output streams is greatly improved, and the larger the buffer, the more efficient it is. (This is the typical sacrifice of space for time)

Remember: when using a buffered stream, flush the buffer to the external data source once the data has been entered. Use close() to achieve the same effect, because each close is flush. Be sure to close the external filter stream.

  1. PipedInputStream and PipedOutputStream

Used to communicate between threads.

PipedOutputStream pos=new PipedOutputStream();

                   PipedInputStream pis=new PipedInputStream();

                   try

                   {

                            pos.connect(pis);

                            new Producer(pos).start();

                            new Consumer(pis).start();

                   }

                   catch(Exception e)

                   {

                            e.printStackTrace();

                   }
Copy the code

9.RandomAccessFile

You can get a file pointer.

Long getFilePointer() gets the position from the start of the file to the file pointer.

Seek (long point) moves the file pointer here.

10, Reader and Writer

1) Java technology uses Unicode to represent strings and characters, and provides a 16-bit version of the stream to handle characters in a similar way.

2) InputStreamReader and OutputStreamWriter serve as the interface between the byte stream and the character stream.

3) If a Reader and Writer are constructed to connect to the stream, the conversion rules switch between using the byte encodings defined by the default platform and Unicode.

4) The difference between byte stream and character stream:

Encoding is converting characters into numbers and storing them in a computer. The process of converting numbers into corresponding characters is called decoding.

Classification of coding methods:

ASCII (numeric, English) :1 character in a byte (all encoding sets are ASCII compatible)

Iso8859-1 (Europe) : 1 character in a byte

Gb-2312 /GBK: A character consists of two bytes

Unicode: 1 character in two bytes (slow network transmission)

Utf-8: Variable-length bytes, one byte for English, two or three bytes for Chinese characters.

BufferedReader method: readLine():String

PrintWriter method: println(… .string,Object, etc.) and write()

  1. Random access file

1) Two interfaces are implemented: DataInput and DataOutput;

2) As long as the file can be opened, it can read and write;

3) Through the file pointer can read and write file specified location;

4) Access all read() and write() operations in DataInputStream and DataOutputStream;

5) Move method in file:

A. long getFilePointer(): Returns the current position of the file pointer.

B. Void seek(long pos): Sets the file pointer to a given absolute position.

C. long length(): Returns the length of the file.

12. Coding problems:

Encoding method:

Each character corresponds to an integer.

Different countries have different codes. When the encoding and decoding methods are not unified, garbled codes will be generated.

Because the United States was the first to develop software, so every code is upward compatible with ASCII so there is no gibberish in English.

Iso-8859-1 Western characters

GB2312…… rong

                   GBK

                   Big5

                   Unicode

                   UTF-8

Supplement:

Byte stream end returns -1

The end of a character stream returns NULL

EOFException is returned at the end of the object stream

——— > Exceptions are often used in process control and are also a return form of a method.