File class (java.io.File)

IO package. 2. File is a class that can have a constructor to create its objects. This object corresponds to a File (.txt.avi.doc.ppt.mp3.ipg) or File directory 3. File class object and platform independent methods in 4. File, only related to how to create, delete, rename and so on. 5. Objects of the File class are often taken as arguments to the constructor of the concrete class of an IO streamCopy the code

Path:

Absolute path: the complete file path including the drive letter Relative path: the path of the file in the current file directoryCopy the code

Method of the File class

1. Access the file name getName() to obtain the file name getPath() to obtain the file path getAbsoluteFile() to obtain the absolute file name getAbsolutePath() to obtain the absolute file path getParent() to obtain the previous file directory RenameTo (File newName) Change a File to another File 2. CanWrite () is writable canRead() is readable isFile() is a file isDirectory() is a directory 3. Get general file information lastModified() get the last modification time of the file length() get the size of the file 4. File operation related createNewFile() Create a file delete() Delete a file or directory 5. MkDir () creates a file directory, returns true only if the upper file directory exists. Create list() to get the File directory for File. ListFiles () to get the File object for FileCopy the code

2. IO streams

IO principle:

Input: External data (data of storage devices, such as disks and cD-RoMs) in the heap to the program (memory) output: Program (memory) data is output to storage devices, such as disks and CD-ROMsCopy the code

I/O flow classification

According to the operation data unit: byte stream (8bit), character stream (16bit) according to the data flow direction: input flow, output flow according to the role of the flow is divided into node flow, processing flowCopy the code
(Abstract base class) Byte stream Characters of the flow
The input stream InputStream Reader
The output stream OutputStream Writer
1. Java IO flow involves more than 40 classes, in fact, very regular, are derived from the above four abstract base classes 2. All subclass names derived from these four classes are suffixed with the name of their parent classCopy the code

IO stream system

classification Byte stream Characters of the flow Byte stream Characters of the flow
Abstract base class InputStream OutputStream Reader Writer
Access to the file FileInputStream FileOutputStream FileReader FileWriter
Access to an array ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter
Access to pipe PipedInputStream PipedOutputStream PipedReader PipedWriter
Access string StringReader StringWriter
Buffer flow BufferedIputStream BufferedOutputStream BufferedReader BufferedWriter
Transformation flows InputStreamReader OutputStreamWriter
Object flow ObjectInputStream ObjectOutputStream
FilterInputStream FilterOutputStream FilterRead FilterWriter
Printing flow PrintStream PrintWriter
Push back the input stream PushbackInputStream PushbackReader
Special flow DataInputStream DataOutputStream

The file flow is the node flow and the buffer flow is the processing flow

IO stream application

Copy files using FileInputStream and FileOutputStream

    public void fileCapy(String src, String dest) {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(new File(src));
            fos = new FileOutputStream(new File(dest));
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
Copy the code

Copy text using FileReader and FileWriter (for non-text files, use byte stream only)

    public void textCapy(String src, String dest) {
        FileReader fr = null;
        FileWriter fw = null;

        try {
            fr = new FileReader(new File(src));
            fw = new FileWriter(new File(dest));
            char[] chars = new char[1024];
            int length;
            while ((length = fr.read(chars)) != -1) {
                fw.write(chars, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
Copy the code

The file SRC corresponding to the input stream must exist; otherwise, FileNotFoundException is abnormal

The dest file corresponding to the output stream may not exist and will be created automatically during execution

Iv. Processing flow – buffer flow (can improve the efficiency of file operation)

Copy files using BufferedInputStream, BufferedOutputStream

    public void bufferedFileCapy(String src, String dest) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(new FileInputStream(new File(src)));
            bos = new BufferedOutputStream(new FileOutputStream(new File(dest)));
            byte[] bytes = new byte[1024];
            int length;
            while ((length = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, length);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
Copy the code

Use BufferedReader, BufferedWriter to copy files

    public void bufferedTextCapy(String src, String dest) {
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            br = new BufferedReader(new FileReader(new File(src)));
            bw = new BufferedWriter(new FileWriter(new File(dest)));
            String line = null;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
Copy the code

Processing stream 2 Conversion stream (conversion stream provides conversion between byte stream and character stream)

Conversion streams: InputStreamReader, OutPutStreamWriter

Encoding: string -> byte array

Decode: byte array -> string

Copy files using the transformation stream

public void transform(String src, String dest) { BufferedReader br = null; BufferedWriter bw = null; try { InputStreamReader streamReader = new InputStreamReader(new FileInputStream(new File(src)), "UTF-8"); br = new BufferedReader(streamReader); OutputStreamWriter streamWriter = new OutputStreamWriter(new FileOutputStream(new File(dest)), "UTF-8"); bw = new BufferedWriter(streamWriter); String line = null; while ((line = br.readLine()) ! = null) { bw.write(line); bw.newLine(); bw.flush(); } } catch (IOException e) { e.printStackTrace(); } finally { if (bw ! = null) try { bw.close(); } catch (IOException e) { e.printStackTrace(); } if (br ! = null) try { br.close(); } catch (IOException e) { e.printStackTrace(); }}}Copy the code

Standard input/output streams

Standard input stream: system. in Standard output stream: system. out

public void systemIn() { BufferedReader br = null; try { InputStream in = System.in; InputStreamReader streamReader = new InputStreamReader(in); br = new BufferedReader(streamReader); String strLine; while ((strLine = br.readLine()) ! = null) { System.out.println(strLine); } } catch (IOException e) { e.printStackTrace(); } finally { if (br ! = null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

Print flow

Byte stream: PrintStream

Character stream: PrintWriter

public void printStream(String fileName) { PrintStream printStream = null; try { printStream = new PrintStream(new FileOutputStream(new File(fileName)), true); if (printStream ! = null) System.setOut(printStream); } catch (IOException e) { e.printStackTrace(); } finally { if (printStream ! = null) printStream.close(); }}Copy the code

Data flow

To easily manipulate data of the basic data types of the Java language, you can use data flows

Data output stream

    public void dataOutStream(String fileName) {
        DataOutputStream outputStream = null;
        try {
            outputStream = new DataOutputStream(new FileOutputStream(new File(fileName)));

            outputStream.writeBoolean(true);
            outputStream.writeDouble(10.24);
            outputStream.writeUTF(" Hello World");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
Copy the code

Data input stream

public void dataInStream(String fileName) { DataInputStream inputStream = null; try { inputStream = new DataInputStream(new FileInputStream(new File(fileName))); boolean b = inputStream.readBoolean(); double d = inputStream.readDouble(); String str = inputStream.readUTF(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream ! = null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

Object Streams (ObjectInputStream, ObjectOutputStream)

A processing stream used to store and read objects. Its power is that it can write Java objects to and recover them from data sources

Class to implement serialization:

Implement Serializable interface 2. The Serializable interface should be implemented with static or transient attributes. The Serializable interface cannot be serialized. Class Person implements Serializable {private static Final Long serialVersionUID = 67348253671L; private String name; private Integer age; private Dog dog; public Person(String name, Integer age, Dog dog) { this.name = name; this.age = age; this.dog = dog; } } class Dog implements Serializable{ private String name; public Dog(String name) { this.name = name; }}Copy the code

ObjectOutputStream

Public void objectOutStream(String fileName) {Person Person = new Person("小 小 ", 19, new Dog("小 小 ")); Person person1 = new Person(" brother ", 20, new Dog(" white ")); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream(new File(fileName))); oos.writeObject(person); oos.flush(); oos.writeObject(person); oos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (oos ! = null) { try { oos.close(); } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

ObjectInputStream

public void objectInStream(String fileName) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream(new File(fileName))); Person o = (Person) ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (ois ! = null) { try { ois.close(); } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

Class RandomAccessFile (support random access)

It can serve as an input stream or dilute an output stream. 2. Read and write from the beginning of a file. 3. R: open in read-only mode ② rw: open for reading and writing ③ RWD: open for reading and writing; ④ RWS: open for reading and writing; Synchronize file content and metadata updatesCopy the code

The RandomAccessFile class does the copying of the file

    public void RandomAccessFile(String src, String srcMode, String dest, String destMode) {
        RandomAccessFile accessFile = null;
        RandomAccessFile accessFile1 = null;
        try {
            accessFile = new RandomAccessFile(new File(src), srcMode);
            accessFile = new RandomAccessFile(new File(dest), destMode);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = accessFile.read(bytes)) != -1) {
                accessFile1.write(bytes, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (accessFile != null)
                try {
                    accessFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            if (accessFile1 != null) {
                try {
                    accessFile1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
Copy the code

The RandomAccessFile class completes the override and modification

RandomAccessFile class method: accessfile.readline (); . / / the contents of the read pointer after accessFile getFilePointer (); Accessfile.seek (4); // Locate the current pointer positionCopy the code
public void randomAccessFileSet(String fileName, String mode) { RandomAccessFile accessFile = null; try { accessFile = new RandomAccessFile(new File(fileName), mode); accessFile.seek(4); accessFile.write("sd".getBytes()); } catch (IOException e) {e.printStackTrace(); } finally { if (accessFile ! = null) try { accessFile.close(); } catch (IOException e) { e.printStackTrace(); }}}Copy the code

The RandomAccessFile class completes the insert

public void randomAccessFileAdd(String fileName, String mode) { RandomAccessFile accessFile = null; try { accessFile = new RandomAccessFile(new File(fileName), mode); accessFile.seek(4); byte [] bytes = new byte[1024]; int length; StringBuffer buffer = new StringBuffer(); while ((length = accessFile.read(bytes))! = -1){ buffer.append(new String(bytes, 0, length)); } accessFile.seek(4); Accessfile.write (" Insert content ".getBytes()); accessFile.write(buffer.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (accessFile ! = null) try { accessFile.close(); } catch (IOException e) { e.printStackTrace(); }}}Copy the code