No doubt!This is the clearest article to explain Java.I/O streaming

Table of Contents

Simple combing

Understand

File streams are the basis of io streams, involving buffer streams, which are operations that use io streams in memory. Conversion streams, as the name implies, are conversions between bytes and character streams., to have byte stream and character stream first, object stream, the most important is the serialization and deserialization of classes, which is equivalent to an encapsulated transformation, random access stream, also on the basis of byte stream and character stream.

File Class

Can create new, delete, rename files and directories, but cannot access file contents, access file contents through input/output streams

Simple combing

File Operation

package day12;

import java.io.File;
import java.io.IOException;

public class Test {
    public static void main(String[] args) {
    File f = new File("D:\\test\\abc\\tt.txt");//At this point object f isTt.txtfile
    File f4 = new File("D:\\test\\abc");//This directory
    <!-- File f2 = new File("D:/test/abc/tt.txt");
    File f3 = new File("D:" + File.separator + "test\\abc\\tt.txt");
    File f1 = new File("D:\\test","abc\\tt.txt");//This f1 is alsoTt.txtFile, there are relatively few experiments of this kind-->

    //Note that \ is the path separator in a file, but in java programming a \ means a transferor, in java \ or/is the file separator
    //It's fine too File.separator As file delimiter
    System.out.println(f.getName());//Get File Name
    System.out.println(f4.getName());//Gets the current file name of the text

    File f5 = new File("src/day12/Test.java");//Create file objects using relative paths

    System.out.println(f5.getPath());//Get the path to the file or folder, which is the path written when the new file is created
    System.out.println(f5.getAbsolutePath());//Gets the absolute path of the current file

    System.out.println(f5);
    System.out.println(f5.getAbsoluteFile());//Returns a file object constructed with an absolute path to the current file

    System.out.println(f5.getParent());//Returns the parent path of the current file or folder

            f.renameTo(new File("D:\\test\\abc\\tt1.txt"));//Rename a file or folder

    File f6 = new File("D:\\test\\abc1");
    System.out.println(f6.exists());//Determine whether a file or folder exists

    File f7 = new File("D:\\test\\abc\\tt1.txt");
    System.out.println(f7.canWrite());//Determine whether a file is writable
    System.out.println(f7.canRead());//Determine if the file is readable

    System.out.println(f7.isFile());//Determine if the current file object is a file
    System.out.println(f7.isDirectory());//Determine if the current file object is a folder or directory

    System.out.println(f7.lastModified());//Gets the last modification time of the file, returning a millisecond
    System.out.println(f7.length());//Returns the length of the file in bytes

    File f8 = new File("D:\\test\\abc\\tt2.txt");
    System.out.println(f8.exists());//Determine whether a file exists
    if(!f8.exists()){
        try {
            f8.createNewFile();//Create a new file
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    <!-- f8.delete();//Delete Files

    File f9 = new File("D:\\test\\abc\\cc");
    File f9 = new File("D:\\test\\abc\\cc\\dd");

    f9.mkdir();//Create a single-tier directory. If you use this method to create a multi-tier directory, you have to execute mkdir() one-tier at a time.

    File f10 = new File("D:\\test\\abc\\a\\b\\c");

    f10.mkdirs();//This method is used directly to create a multilayer directory-->

    File f11 = new File("D:\\test");
    String[] fl = f11.list();//Returns the name of a subset of the current folder, including directories and files
    for(String s : fl){
        System.out.println(s);
    }

    File[] fs = f11.listFiles();//Returns a file object that is a subset of the current folder, including directories and files
    for(File ff : fs){
        System.out.println(ff);
    }
}

Recursively traverse files

    public void test(File file){
        if(file.isFile()){
            System.out.println(file.getAbsolutePath() + " Is a file");
        }else{
            System.out.println(file.getAbsolutePath() + " Is a folder");
            //If it is a folder, there may be subfolders or files in this folder
            File[] fs = file.listFiles();//Gets the file object of a subfolder or file under the current folder
            if(fs != null && fs.length > 0){
                for(File ff : fs){

                    test(ff);//recursion

                    if(ff.isFile()){
                        System.out.println(ff.getAbsolutePath() + " Is a file");
                    }else{
                        System.out.println(ff.getAbsolutePath() + " Is a folder");
                        File[] fs1 = ff.listFiles();
                        if(fs1 != null && fs1.length > 0){
                            for(File ff1 : fs1){

                            }
                        }
                    }

                }
            }

        }
    }
}

File Flow: Read and write data streams are file-based operations

Byte streams are very versatile and can be used to manipulate documents of characters, and then other types of files, all using binary conversions

FileInputStream: Byte input stream

public static void testFileInputStream(){
    try {
        FileInputStream in = new FileInputStream("D:/test/abc/tt1.txt");

        byte[] b = new byte[10];//Set up a byte array to receive the contents of the read file

        int len = 0;//Set a length to read data

        //In.read(b);//In.readMethod has a return value, which is the length of the data read. If the last data is read, it will also read backward, at which point the return value is -1
        //That means whenIn.readThe entire file is read when the return value of -1

        while((len = in.read(b)) != -1){
            System.out.println(new String(b,0,len));
            //new String(b,0,len), parameter 1 is an array of buffered data, parameter 2 converts a string from that location of the array, and parameter 3 converts a total of several bytes
        }

        in.close();//Be careful.Stream is closed after use
    } catch (Exception e) {
        e.printStackTrace();
    }
}

FileOutputStream: Byte output stream

public static void testFileOutputStream(){
    try {
        FileOutputStream out = new FileOutputStream("D:/test/abc/tt4.txt");//Specify row tt4 output data
        String str = "knsasjadkajsdkjsa";
        out.write(str.getBytes());//Write data to memory
        out.flush();//Brush in-memory data to hard disk
        out.close();//Close Stream

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

Copy file to specified location

public static void copyFile(String inPath, String outPanth){
    try {
        FileInputStream in = new FileInputStream(inPath);//Read Source File

        FileOutputStream out = new FileOutputStream(outPanth);//Where to Copy

        byte[] b = new byte[100];

        int len = 0;

        while((len = in.read(b)) != -1){
            out.write(b, 0, len);//Parameter 1 is a write buffer array, parameter 2 starts at that position of the array, and parameter 3 is the total length of the array obtained
        }

        out.flush();//Brush data written to memory to hard disk
        out.close();
        in.close();

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

FileReader: Character input stream

public static void testFileReader(String inPath){
    try {
        FileReader fr = new FileReader(inPath);//Object to create file character input stream

        char[] c = new char[10];//Create an array of characters for temporary data

        int len = 0;//Define a read length for an input stream

        while((len = fr.read(c)) != -1){
            System.out.println(new String(c, 0, len));
        }

        fr.close();//Close Stream

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

FileWriter: Character output stream

public static void testFileWriter(String text,String outPath){
    try {
        FileWriter fw = new FileWriter(outPath);
        fw.write(text);//Write to memory
        fw.flush();//Brush data from memory to hard disk
        fw.close();//Close Stream

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

Copy the file to the specified location (character streams are only appropriate if the operation content is a character file)

public static void copyFile(String inPaht, String outPath){
    try {
        FileReader fr = new FileReader(inPaht);
        FileWriter fw = new FileWriter(outPath);

        char[] c = new char[100];

        int len = 0;

        while((len = fr.read(c)) != -1){//Read data
            fw.write(c,0,len);//Write data to memory
        }

        fw.flush();

        fw.close();
        fr.close();

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

Buffer Stream: Read and write data streams are memory-based operations

  • Buffer streams need to be nested on the corresponding node streams, providing buffering for read-write data, improving read-write efficiency, and adding some new methods. For output buffer streams, the written data will be cached in memory first, and using flush() will make the in-memory data write out immediately
  • Simply put, first cache the data in memory and do io operations in memory

BufferedInputStream: Buffered byte input stream

public static void testBufferedInputStream() throws Exception {
    // File Byte Input Stream Object
    FileInputStream in = new FileInputStream("D:\\testdemo\\demo\\src\\day13\\tt.txt");

    // Place file byte input stream into buffer byte input stream object
    BufferedInputStream br = new BufferedInputStream(in);

    byte[] b = new byte[10];

    int len = 0;

    while ((len = br.read(b)) != -1) {
        System.out.println(new String(b, 0, len));
    }

    // When closing a stream, turn it off one by one at the earliest turn on
    br.close();
    in.close();
}

BufferedOutputStream: Buffered byte input stream

public static void testBufferedOutputStream() throws Exception {
    // Create Byte Output Stream Object
    FileOutputStream out = new FileOutputStream("D:\\testdemo\\demo\\src\\day13\\tt1.txt");

    // Put Byte Output Stream Object in Buffered Byte Output Stream
    BufferedOutputStream bo = new BufferedOutputStream(out);

    String s = "hello world";

    bo.write(s.getBytes());// Write to memory

    bo.flush();// Brush to hard disk

    // When closing a stream, turn it off one by one at the earliest turn on
    bo.close();
    out.close();
}

Buffer Stream Implements File Copying

public static void copyFile() throws Exception {
    // Buffer Input Stream
    BufferedInputStream br = new BufferedInputStream(
            new FileInputStream("D:\\testdemo\\demo\\src\\day13\\tt1.txt"));

    // Buffer Output Stream
    BufferedOutputStream bo = new BufferedOutputStream(
            new FileOutputStream("D:\\testdemo\\demo\\src\\day13\\tt2.txt"));

    byte[] b = new byte[1024];

    int len = 0;// Set a length of data that cannot be read untilBr.readMethod executes to the end (for example, only hello is in the file)
                // world, after the last read d, the return value is -1)

    while ((len = br.read(b)) != -1) {
        bo.write(b, 0, len);// Write to memory
    }

    bo.flush();// Brush to Hard Disk

    bo.close();
    br.close();
}

BufferedReader: Buffer character input stream

public static void testBufferedReader() throws Exception {
    FileReader r = new FileReader("D:\\testdemo\\demo\\src\\day13\\tt.txt");

    BufferedReader br = new BufferedReader(r);

    char[] c = new char[100];

    int len = 0;

    while ((len = br.read(c)) != -1) {// br.read(c) Read next to the last character of the file, and the return value is -1
        System.out.println(new String(c, 0, len));
    }
    br.close();
    r.close();
}

BufferedWriter: Buffer character output stream

public static void testBufferedWriter() throws Exception {
    FileWriter fw = new FileWriter("D:\\testdemo\\demo\\src\\day13\\tt3.txt");

    BufferedWriter bw = new BufferedWriter(fw);

    String s = "hello world!!!!";

    bw.write(s);

    bw.flush();

    bw.close();
    fw.close();
}

Buffered Character Stream Copy File

public static void copyFile() throws Exception {
    BufferedReader br = new BufferedReader(new FileReader("D:\\testdemo\\demo\\src\\day13\\tt3.txt"));

    BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\testdemo\\demo\\src\\day13\\tt4.txt"));

    char[] c = new char[100];

    int len = 0;

    while ((len = br.read(c)) != -1) {
        bw.write(c, 0, len);
    }

    bw.flush();

    bw.close();
    br.close();
}

Conversion Flow

  • Convert Byte Input Stream to Character Input Stream Note that when converting a character stream, set the character set encoding to match the encoding of the data of the file being read or the chaotic InputStreamReader will appear
  • All files are in encoding format. For us, TXT and java files generally have three encodings, ISO8859-1, Western European encoding. They are pure English encoding, not Chinese characters, GBK and UTF-8. These two encodings are important and applicable to English. We usually use UTF-8 encoding.

InputStreamReader: Converts a byte input stream to a character input stream

public static void testInputStreamReader() throws Exception {
    FileInputStream fs = new FileInputStream("D:\\testdemo\\demo\\src\\day13\\tt5.txt");

    // Convert Byte Stream to Character Stream
    InputStreamReader in = new InputStreamReader(fs, "GBK");// Parameter 1 is a byte stream and parameter 2 is an encoding
    //InputStreamReader in = new InputStreamReader (fs,'UTF-8'); //Parameter 1 is a byte stream, and parameter 2 is an encoding

    char[] c = new char[100];
    int len = 0;

    while ((len = in.read(c)) != -1) {
        System.out.println(new String(c, 0, len));
    }

    in.close();
    fs.close();
}

OutputStreamReader: Convert byte output stream to character output stream

public static void testOutputStreamWriter() throws Exception {
    FileOutputStream out = new FileOutputStream("D:\\testdemo\\demo\\src\\day13\\tt6.txt");

    //OutputStreamWriter os = new OutputStreamWriter(out, "UTF-8");
    OutputStreamWriter os = new OutputStreamWriter(out, "GBK");

    os.write("Hello Hello");
    os.flush();

    os.close();
    out.close();
}

Standard input-output stream

  • System.in( default input keyboard): Type is InputStream
  • System.out( Default Output Display): Type is PrintStream, which is a subclass of OutputStream FilterOutputStream

Standard input stream

public static void testSystemIn() throws Exception {
    // Create an input stream that receives keyboard input data
    InputStreamReader is = new InputStreamReader(System.in);

    // Put the input stream in the buffer stream
    BufferedReader br = new BufferedReader(is);

    String str = "";// Define a string that temporarily receives data

    while ((str = br.readLine()) != null) {
        System.out.println(str);
    }

    br.close();
    is.close();
}

Writes the console input to the specified TXT file and terminates the program when the string over is received

public static void write2TXT() throws Exception {
    // Create an input stream that receives keyboard input data
    InputStreamReader is = new InputStreamReader(System.in);

    // Put the input stream in the buffer stream
    BufferedReader br = new BufferedReader(is);

    BufferedWriter out = new BufferedWriter(new FileWriter("D:\\testdemo\\demo\\src\\day13\\tt7.txt"));

    String line = "";

    while ((line = br.readLine()) != null) {
        if (line.equals("over")) {
            break;
        }
        // Each line read is written to the specified TXT file
        out.write(line);
    }

    out.flush();
    out.close();
    br.close();
    is.close();

}

Print Stream (Understanding)

PrintStream/PrIntWriter: System.out.printlnetc.

Data Flow (Understanding): Used exclusively for reading and writing basic data types

DataInputStream: Data output stream

Data of the basic data type written to the file by the data output stream is garbled and cannot be directly identified. A data input stream is required to read the DataOutputStream

public static void testDataOutputStream() throws Exception {
    DataOutputStream out = new DataOutputStream(new FileOutputStream("D:/testdemo/demo/src/day13/tt8.txt"));

    //out.writeBoolean(true);
    out.writeDouble(1.35d);
    //out.writeInt(100);

    out.flush();
    out.close();

}

DataOutputStream: Data input stream

If you write with a writeDouble, you read with a readDouble DataInputStream

public static void testDataInputStream() throws Exception {
    DataInputStream in = new DataInputStream(new FileInputStream("D:/testdemo/demo/src/day13/tt8.txt"));

    System.out.println(in.readDouble());

    in.close();
}

Object Flow (Serialization and Deserialization): Converts an object into a data stream for reading and writing

ObjectInputStream: Serialization of objects

public static void testSerialize() throws Exception {
    // Defines the output stream of an object, and serializes the object to a specified file
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:/testdemo/demo/src/day13/tt9.txt"));

    Person p = new Person();
    p.name = "zhangsan";
    p.age = 11;

    out.writeObject(p);
    out.flush();// Refresh Data to Hard Disk

    out.close();
}

ObjectOutputStream: Deserialization of objects

public static void testDeserialize() throws Exception {
    // Creates an object input stream object that reads the stream of serialized objects from a specified file
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:/testdemo/demo/src/day13/tt9.txt"));

    Object obj = in.readObject();

    Person p = (Person) obj;

    // The classes used for serialization and deserialization at this time are not day13.Person and day13, respectively.Test.Person
    // At this point deserialization has an exception day13.Person cannot be cast to day13.test.Person
    //day13.test.Person p = (day13.test.Person)obj;

    System.out.println(p.name);
    System.out.println(p.age);

    in.close();

}

RandomAccessFile: Access file streams freely: insert location, read location, storage location freely

  • The construction of RandomAccessFile has two parameters, parameter 1 is the path of the read-write file
  • Parameter 2 specifies the access mode of RandomAccessFile
  • r:Open as read-only
  • rw: open for reading and writing
  • rwd: open for reading and writing; synchronize updates to file contents
  • rws: Open for reading and writing; synchronize updates to file contents and metadata
  • The most common are r and rw

Read files freely

public static void testRandomAccessFileRead() throws Exception {
    RandomAccessFile ra = new RandomAccessFile("D:/testdemo/demo/src/day13/tt10.txt", "r");

    //ra.seek(0); //Set the starting point for reading the contents of the file
    ra.seek(8);// Read from anywhere in the file by setting a starting point for reading the contents of the file

    byte[] b = new byte[1024];

    int len = 0;

    while ((len = ra.read(b)) != -1) {
        System.out.println(new String(b, 0, len));
    }

    ra.close();
}

Save files freely

public static void testRandomAccessFileWrite() throws Exception {
    RandomAccessFile ra = new RandomAccessFile("D:/testdemo/demo/src/day13/tt10.txt", "rw");

    //ra.seek(0); //Set the starting point for writing, 0 means write from the beginning
    // Note: If you start writing at the beginning or somewhere in the middle of the file, you will overwrite the original content of equal length with the written content
    ra.seek(ra.length());// Set the starting point for writing,ra.length() means to write from the end of the file, that is, to append the file

    ra.write("Hello".getBytes());

    ra.close();
}

Tags: Java encoding Programming

Posted on Wed, 03 Jun 2020 09:25:29 -0700 by d~l