Java stream and file operation

Posted by mds1256 on Wed, 26 Jan 2022 13:50:44 +0100

Basic concepts of data flow

In Java, the data transmission between different data sources and programs is abstractly expressed as a stream,

Used to achieve relatively unified and simple input / output (I / O)

In Java IO package defines many types of interfaces and classes to realize the data input / output function, also known as I/O flow type;

Using these data, a data transmission channel, I/O flow, can be established between the program and the data source;

Data can then be read from or written to the stream in a basically uniform and concise manner.

Overall flow chart

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9Tn3YdyI-1626087660198)(D:\java development \ Java notes \ images\IO stream. png)]

File related operations

create a file

new File(String pathname)//Build a File object based on the path
new File(File parent,String child)//Build according to parent directory file + child path
new File(String parent,String child)//Build according to parent directory + child path

Method for obtaining relevant information of file

getName			Get file name
getAbsplutePath	Get absolute path
getParent		Gets the pathname of the parent directory
length			Gets the file byte size
exists			Does the file exist
isFile			Is it a file
isDirectory		Is it a directory

Directory operation and file deletion

mkdir 	Create first level directory
mkdirs	Create multi-level directory
delete	Delete an empty directory or file

Java IO stream principle

1.I/O is the abbreviation of Input/Output. I/O technology is used to process data transmission. Such as reading and writing files, network communication, etc.

2. In Java program, the input / output operation of data is carried out in the way of "Stream".

3.Java. The IO package provides classes and interfaces for various streams to obtain different kinds of data and input or output data through methods.

Classification of flow

According to different operation data units, it is divided into byte stream and character stream (by character)

According to the flow direction of data flow, it is divided into input flow and output flow

According to the different roles of the flow, it can be divided into node flow, processing flow / packaging flow

Abstract base classByte streamCharacter stream
Input streamInputStreamReader
Output streamOutputStreamWriter

Java's io stream has more than 40 classes, which are actually very regular and derived from four abstract base classes

The subclass names derived from the four classes all use the parent class name as the suffix of the subclass class name

FileInputStream

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class NewFile03 {
    public static void main(String[] args) throws IOException {
        //Declared path address
        String filepath = "D:\\FFOutput\\1.txt";
        //Declaration conditions
        int read =0;
        //Create an instantiation of the byte input stream of the import path address for reading files
        FileInputStream fileInputStream = new FileInputStream(filepath);
        //Read a byte of data from this input stream. No input is available. Block the method
        //Returns - 1, indicating that the reading is complete
        while ((read = fileInputStream.read()) != -1){
            //Convert to char display
            System.out.print((char) read);
        }
        //Close input stream
        fileInputStream.close();
    }
}

FileOutPutStream

import java.io.FileOutputStream;
import java.io.IOException;


public class FileOutPutStream01 {
    public static void main(String[] args) throws IOException {
        writeFile();
    }
    public static void writeFile() throws IOException {
        //Declare a path
        String filePath = "D:\\FFOutput\\1.txt\\";
        //Create a FileOutPutStream instance
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);
        String str = "A teenager joined the knight temple to save his mother. Miracles and tricks were constantly performed on him. In this world where the six human shrines and the 72 column demon gods of the demon family collide with each other, can he ascend the God seal throne, which symbolizes the highest glory of the knight";
        //Output string to file 1 Txt
        //getBytes() converts a string to a byte array
        fileOutputStream.write(str.getBytes());
        //Close input stream
        fileOutputStream.close();
    }
}

File copy

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) throws IOException {
        copyFile();
    }
    public static void copyFile() throws IOException {
        //Thinking analysis of copying files
        //1. Create the input stream of the file and read the file into the program
        //2. Create the output stream of the file and write the read file data to the specified file
        //Start location of file
        String filePath = "D:\\FFOutput\\first\\Divine seal throne.txt";
        //Final location of copied files
        String FinalFilePath = "D:\\FFOutput\\second\\Divine seal throne.txt";
        //Read file instantiation
        FileInputStream fileInputStream = new FileInputStream(filePath);
        //Output file instantiation
        FileOutputStream fileOutputStream = new FileOutputStream(FinalFilePath);
        //Create a byte array
        byte[] buf = new byte[10000];
        //Declaration conditions
        int readLen = 0;
        //Cycle to read the bytes in the start file until it is finished
        while ((readLen = fileInputStream.read(buf))!=-1){
            //An array of output to the output byte stream
            fileOutputStream.write(buf);
        }
        //Close flow operation
        fileInputStream.close();
        fileOutputStream.close();
    }
}

File character stream

FileReader and FileWrite are character streams;

FileReader related methods

1,new FileReader(File/String)

2.read: each time a single character is read, the character is returned. If it reaches the end of the file, it returns - 1

3.read(char []): batch read multiple characters into the array and return the number of characters read. If it reaches the end of the file, return - 1

Related API:

1.new String(char []): convert char [] to String

2. New String (char [], off, len): convert the specified part of char [] to String

FileWrite common methods

1.new FileWriter(File/String): overwrite mode, which is equivalent to that the pointer of the stream is at the head end

2.new FileWriter(File/String,true): append mode, which is equivalent to the flow pointer at the end

3.write(int): write a single character

4.write(char []): write the specified array

5.write(char[],off,len) writes the specified part of the specified array

6.write(string): write the entire string

7.write(string,off,len): write the specified part of the string

Note: after the FileWriter is used, it must be closed or flushed, otherwise the specified file cannot be written

FileReader

import java.io.FileReader;
import java.io.IOException;

public class FileReader01 {
    public static void main(String[] args) throws IOException {
        //Declaration file path
        String filePath = "D:\\FFOutput\\first\\Dionysus.txt\\";
        //Declaration conditions
        int data = ' ';
        //Create character read stream instantiation
        FileReader fileReader = new FileReader(filePath);
        //Read is used for cyclic reading, and a single character is read
        while ((data = fileReader.read()) != -1){
            System.out.print((char) data);
        }
        //Close flow
        fileReader.close();
    }
}

FileWriter

import java.io.FileWriter;
import java.io.IOException;

public class FileWriter01 {
    public static void main(String[] args) throws IOException {
        String str = " A lazy teenager, who chose to learn the light magic that no one cares about because of his character, inadvertently stepped close to the wheel of fate and became the legendary great mage step by step. It was his efforts that ended the boundary between the East and the west, made the whole continent no longer divided by race, and became the son of light respected by all ethnic groups in future generations.";
        String filePath = "D:\\FFOutput\\first\\Son of light.txt\\";
        FileWriter fileWriter = new FileWriter(filePath);
        
        fileWriter.write(str);
        fileWriter.close();
    }
}

Node flow and processing flow

classificationByte input streamByte output streamCharacter input streamCharacter output stream
Abstract base classInputStreamOutPutStreamReaderWriter
access filesFileInputStreamFileOutPutStreamFileReaderFileWriterNode flow
Access arrayByteArrayInputStreamByteArrayOutputStreamCharArrayReaderCharArrayWriterNode flow
Access pipelinePipedInputStreamPipedIntputStreamPipedReaderPipedWriterNode flow
Access stringStringReaderStringWriterNode flow
Buffer streamBufferedInputStreamBufferedOutputStreamBuffteredReaderBufferedWriterProcessing flow
Conversion flowInputStreamReaderOutputStreamReaderProcessing flow
Object flowObjectInputStreamObjectOutputStreamProcessing flow
Abstract base classFilterInputStreamFilterOutputStreamFilterReaderFilterWriterProcessing flow
Print streamPrintStreamPrintWriterProcessing flow
Push back input streamPushbackInputStreamPushbackReaderProcessing flow
Special flowDataInputStreamDataOutputStreamProcessing flow

Differences and relations between node flow and processing flow

1. Node flow is the underlying source flow / low-level flow, which is directly connected with the data source

2. Processing flow packaging node flow can not only eliminate the implementation differences of different node flows, but also provide convenient methods to complete input and output

3. The processing flow (wrapping flow) wraps the node flow, using the decorator design pattern, and will not be directly connected to the data source

The function of processing flow is mainly reflected

1. Performance improvement: mainly increase the buffer to improve the efficiency of input and output

2. Portability of operation: the processing stream may provide a series of convenient methods to input and output large quantities of data at one time, which is more flexible and convenient to use

BufferedReader

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Buffered01 {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\FFOutput\\second\\Divine seal throne.txt\\";
        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String Line;
        while ((Line = bufferedReader.readLine())!=null){
            System.out.println(Line);
        }
        bufferedReader.close();
    }
}

BufferedWriter

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BudderedWriter01 {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\FFOutput\\second\\Son of light.txt\\";
        //Create instantiation
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));
        //Write text
        bufferedWriter.write("The regret of the third life and the remembrance of the third life");
        //Line feed
        bufferedWriter.newLine();
        bufferedWriter.write("Sky green ancient lotus, ten thousand Dharma stars!");
        bufferedWriter.newLine();
        bufferedWriter.write("A shackle, chain thousands of star fields");
        bufferedWriter.newLine();
        bufferedWriter.write("A heart rises and falls at dawn.");
        bufferedWriter.close();
    }
}

Character processing stream copy file

import java.io.*;

public class Copy01 {
    public static void main(String[] args) throws IOException {
        String srcFilePath = "D:\\FFOutput\\first\\Dionysus.txt\\";
        String destFilePath = "D:\\FFOutput\\second\\Dionysus.txt\\";
        BufferedReader br = new BufferedReader(new FileReader(srcFilePath));
        BufferedWriter bw = new BufferedWriter(new FileWriter(destFilePath));
        String line;
        while((line = br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            System.out.println("File copied successfully...");
        }
        br.close();
        bw.close();
    }
}

Byte processing stream copy file

public class copy02 {
    public static void main(String[] args) throws IOException {
        String srcFilePath = "D:\\FFOutput\\first\\Long HaoChen.jpg\\";
        String destFilePath = "D:\\FFOutput\\second\\456.jpg\\";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFilePath));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
        byte[] buff = new byte[10000];
        int readLen = 0;
        while((readLen = bis.read(buff))!=-1){
           bos.write(buff,0,readLen);
            System.out.println("File copy complete");
        }
        bis.close();
        bos.close();
    }
}

Object processing flow

serialization and deserialization

1. Serialization is to save the value and data type of data when saving data

2. Deserialization is to recover the data value and data type when recovering the data

3. If an object needs to support serialization mechanism, its class must be serializable

Class is serializable. This class must implement two interfaces: serializable and Externalizable

matters needing attention

1. Consistent reading and writing order

2. It is required to implement serialization or deserialization of objects. Serializable needs to be implemented

3. It is recommended to add SerivalVersionUID to serialized classes to improve version compatibility

4. When serializing an object, all attributes in it are serialized by default, except for members decorated with static or transient

5. When serializing an object, it is required that the type of the attribute inside should also implement the serialization interface

6. Serialization is inheritable, that is, if a class has implemented serialization, all its subclasses have implemented serialization by default

Objectoutputstream (serialization)

import java.io.*;

public class ObjectOutPutStream_ {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\FFOutput\\second\\oos.txt\\";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
        oos.writeInt(100);
        oos.writeBoolean(true);
        oos.writeDouble(4.5);
        oos.writeUTF("The blue sea, the Sheng and Xiao sound");
        oos.writeObject(new Dog("have one's wish fulfilled",10));
        oos.close();
    }
}
class Dog implements Serializable{
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Objectinputstream (deserialization)

import java.io.*;

public class Pbject02 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String filePath = "D:\\FFOutput\\second\\oos.txt\\";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        Object dog = ois.readObject();
        System.out.println("Operation type"+dog.getClass());
        System.out.println("dog information"+dog);

    }
}

Conversion flow

introduce

1.IntputStreamReader: subclass of Reader, which can wrap intputstream (byte stream) into Reader (character stream)

2.OutputStreamWriter: subclass of Writer, which implements wrapping OutputStream (byte stream) into Writer (character stream)

3. When processing plain text data, if using character stream is more efficient and can effectively solve the Chinese problem, it is recommended to convert byte stream into character stream

4. You can specify the encoding format (utf-8, gbk, gb2312, etc.) when using

IntputStreamReader

import java.io.*;

public class InputStreamReader01 {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\FFOutput\\second\\Son of light.txt\\";
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath),"utf-8");
        BufferedReader br = new BufferedReader(isr);
        String s= br.readLine();
        System.out.println("Read content="+s);
        br.close();
    }
}

OutoutStreamWriter

import java.io.*;

public class XieRu {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\FFOutput\\first\\Knight of glory.txt";
        OutputStreamWriter  gbk =  new OutputStreamWriter(new FileOutputStream(filePath),"gbk");
        gbk.write("Holding the sun and moon and picking the stars, there is no one like me in the world");
        gbk.close();
    }
}
       String s= br.readLine();
        System.out.println("Read content="+s);
        br.close();
    }
}

OutoutStreamWriter

import java.io.*;

public class XieRu {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\FFOutput\\first\\Knight of glory.txt";
        OutputStreamWriter  gbk =  new OutputStreamWriter(new FileOutputStream(filePath),"gbk");
        gbk.write("Holding the sun and moon and picking the stars, there is no one like me in the world");
        gbk.close();
    }
}

Topics: Java