Input and output processing

Java IO

  • Input (in) / output (out)

  • Persistent storage

  • File, memory, keyboard (data source) - > program - > file, memory, console (destination)

    • Data source - > program: input (read data) in

    • Program - > console: output (write data) out

  • File: a collection of permanently stored data

  • File storage media: USB flash disk, hard disk

File class

  • java.io.File

  • The File class accesses File properties

  • File can refer to a file or * * directory**

Method nameexplain
boolean exists()Determine whether the file or directory exists
boolean isFile()Determine whether it is a file
boolean isDirectory()Determine whether it is a directory
String getPath()Returns the relative pathname of the file represented by this object
String getAbsolutePath()Returns the absolute pathname of the file represented by this object
String getName()Returns the name of the file or directory represented by this object
boolean delete()Delete the file or directory specified by this object
boolean createNewFile()Create an empty file with a name and do not create a folder
long length()Returns the length of the file in bytes. If the file does not exist, 0L is returned
import java.io.*;
//File operation: file creation, obtaining file related information and deleting files
public class FileDemo {
    //create a file
    public void create(File file){
        if (!file.exists()){
            //If the file does not exist, it is created
            try {
                file.createNewFile();
                System.out.println("File created!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //Get file information
    public void showFileInfo(File file){
        if (file.exists()){
            //It's a file
            if (file.isFile()){
                System.out.println("File name:"+file.getName());
                System.out.println("Relative path to file:"+file.getPath());
                System.out.println("Absolute path to file:"+file.getAbsolutePath());
                System.out.println("The file size is:"+file.length()+"Bytes");
            }
            //It's a directory
            if (file.isDirectory()){
                System.out.println("This file is a directory!");
            }
        }else {
            System.out.println("File does not exist!");
        }
    }

    //Delete file
    public void delete(File file){
        if (file.exists()){
            file.delete();
            System.out.println("The file has been deleted!");
        }
    }

    //test method
    public static void main(String[] args) {
        FileDemo fileDemo = new FileDemo();
        //File file = new File("C:/Disks/text.txt");
        File file = new File("text.txt");
        //fileDemo.create(file);
        //fileDemo.showFileInfo(file);
        fileDemo.delete(file);

    }
}

flow

  • A stream is an ordered sequence of data
  • A channel that sends information in a first in first out manner

Data source = = > program: input stream (read data) InputStream

Program = = > console: output stream (write data) OutputStream

  • Classification by flow direction:

    Output stream: OutputStream and Writer as base class (parent class)
    Input stream: InputStream and Reader as base classes

  • By data processing unit:

    Byte stream (8 bits):

    • Input (InputStream)

    • Output (OutputStream)

    Character stream (16 bits):

    • Input (Reader)
    • Output (Writer)

InputStream/OutputStream is an abstract class. Only subclasses can be used to create a new object

InputStream class

  • Byte input stream: read

    common method

    Method nameexplain
    int read()Read out the bytes of the data source in turn. The byte by byte reading returns the integer expression of the byte. If it reaches the end of the input stream, it returns - 1
    int read(byte[] b)Read several bytes from the input stream, save these bytes into array b, and return the number of bytes read. If the end of the input stream is read, return - 1
    int read(byte[] b,int off,int len)Read a number of bytes from the input stream and save them into array b. off refers to the starting subscript of the data in the byte array, and len refers to the number of bytes to be read. Returns the number of bytes read. If the end of the input stream is read, it returns - 1
    void close()Turn off the input stream
    int available()The number of bytes that can be read from the input stream

Subclass: InputStream

Construction method:

  • FileInputStream(File file)
  • FileInputStream(String name)

Reading steps:

  1. Introduce resources (related classes)
  2. Create FileInputStream object
  3. Read the file with the help of the read() method of the FileInputStream object
  4. Close input stream
//1. Introduction of resources
import java.io.*;
//Read operation of file through byte input stream
public class FileInputStreamDemo {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            //2. Create FileInputStream object
             fileInputStream = new FileInputStream("c:/Disks/text.txt");
            System.out.println("Number of bytes that can be read:"+fileInputStream.available());
            //3. Read the file with the read() method of FileInputStream object
           /* int data;
            while ((data = fileInputStream.read()) != -1){
                System.out.print((char)data);
            }*/
            //Read the file with the read(byte[] b) method of FileInputStream object
            byte[] b = new byte[1024];
            int data;
            while ((data = fileInputStream.read(b)) != -1){
                //Bytes are read into byte array b, and the contents of array b need to be output circularly
                //for (int i = 0; i < b.length; i++) {
                for (int i = 0; i < data; i++) {
                    System.out.print((char)b[i]);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {//In order to ensure successful reading, the stream can be closed and the closure is written to finally
            //4. Close the input stream
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

OutputStream class

  • Byte output stream: write

Common methods:

Method nameexplain
void write(int d)Write bytes to the output stream
void write(byte[] b)Writes a byte array to the output stream
void write(byte[] b,int off,int len)Write a byte array into the output stream. Off means to start writing out from the off position of the byte array, and Len means to write out the bytes of len length
void close()Close output stream
void flush()Force the data of the buffer to be written out to the output stream

FileOutputStream: subclass

Construction method:

  • FileOutputStream(File file)

  • FileOutputStream(String name)

  • FileOutputStream(String name,boolean append)

    1. The first two construction methods will overwrite the contents of the original file when writing data
    2. To append from the original file, you need to add a boolean type parameter

Write steps:

  1. Introduce resources (related classes)
  2. Create FileOutputStream object
  3. Read the file with the help of the write() method of the FileOutputStream object
  4. Close output stream
//1. Introduction of resources
import java.io.*;
//Write to file with byte output stream
public class FileOutputStreamDemo {
    public static void main(String[] args) {
        FileOutputStream fileOutputStream = null;

        try {
            //2. Create byte output stream object (FileOutputStream)
            //fileOutputStream = new FileOutputStream("c:/Disks/text.txt");
            //The content of the original text is not overwritten, but added at the end of the original text
            fileOutputStream = new FileOutputStream("c:/Disks/text.txt",true);
            //3. Call the write() method of the byte output stream item to write the file
            String info = "Study hard Java";
            //Break the written string into a byte array
            byte[] infos = info.getBytes();
            fileOutputStream.write(infos,0,infos.length);
            System.out.println("The file has been updated!");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4. Turn off the output stream
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Input output comprehensive exercise

import java.io.*;

//With the help of byte input and output stream, the file copy (read and write) is realized
//c: Who decides my youth tex  ---> c:\Disks\text. txt
public class InAndOut {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;//Input stream
        FileOutputStream fileOutputStream = null;//Output stream

        try {
            fileInputStream = new FileInputStream("C:/Source/My youth who call the shots.txt");
            fileOutputStream = new FileOutputStream("c:/Disks/text.txt",true);
            byte[] words = new byte[1024];
            int len = -1;
            //The contents of the file are read out and stored in the words array
            while ((len=fileInputStream.read(words))!=-1){
                //Write out the byte array words to the output stream
                fileOutputStream.write(words,0,len);

            }
            System.out.println("File copy completed!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

Reader class

  • Character input stream

    Reader-InputStreamReader-FileReader-BufferedReader
    readLine()

    Common methods:

Method nameexplain
int read()Read the characters of the data source in turn. Reading one character by one returns the integer expression of the character. If it reaches the end of the input stream, it returns - 1
int read(byte[] b)Read several characters from the input stream, save these characters into array b, and return the number of characters read. If you read the end of the input stream, return - 1
int read(byte[] b,int off,int len)Read several characters from the input stream and save them into array b. off refers to the starting subscript of the data in the character array, and len refers to the number of characters you want to read. Returns the number of characters read. If the end of the input stream is read, it returns - 1
void close()Turn off the input stream
int available()The number of characters that can be read from the input stream

FileReader: grandchild

Construction method:

  • FileReader(File file)
  • FileReader(String name)

Reading steps:

  1. Introduce resources (related classes)
  2. Create FileReader object
  3. Read the file with the read() method of FileReader object
  4. Close input stream
import java.io.*;

//Read files with the help of character input stream FileReader
public class FileReaderDemo {
    public static void main(String[] args){
        FileReader fileReader = null;
        try {
            //2. Create character input stream FileReader object
            fileReader = new FileReader("c:/Disks/text.txt");
            //3. Call the FileReader object read() method to read the file

            StringBuffer s = new StringBuffer();
            char[] ch = new char[1024];
            int len = -1;
            while ((len = fileReader.read(ch))!=-1){
                s.append(ch);
            }
            System.out.println(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Close the input stream
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Chinese garbled Code: InputStreamReader

  • The file coding format is inconsistent with the program environment coding format

  • Character encoding format

    • GBK
    • GB2312
    • UTF-8
  • terms of settlement

    1. Manually adjust the coding format of both ends to be consistent
    2. Use Reader subclass InputStreamReader
      • InputStreamReader(InputStream in)
      • InputStreamReader(InputStream in,String charsetName)
import java.io.*;
import java.io.IOException;

//Read files with the help of character input stream FileReader
public class FileReaderDemo {
    public static void main(String[] args){
        Reader reader = null;
        try {
            //Get local encoding format
            System.out.println(System.getProperty("file.encoding"));
            //2. Create character input stream InputStreamReader object
            FileInputStream fileInputStream = new FileInputStream("c:/Disks/text.txt");
            reader = new InputStreamReader(fileInputStream,"GBK");
            //3. Call the FileReader object read() method to read the file

            StringBuffer s = new StringBuffer();
            char[] ch = new char[1024];
            int len = -1;
            while ((len = reader.read(ch))!=-1){
                s.append(ch);
            }
            System.out.println(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Close the input stream
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

BufferedRead class: subclass

  • With buffer
  • Read content: readLine() method
//1. Introduction of resources
import java.io.*;
//Read files with the help of character input stream FileReader
public class BufferedReaderDemo {
    public static void main(String[] args){
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            //Get local encoding format
            System.out.println(System.getProperty("file.encoding"));
            //2. Create character input stream InputStreamReader object
            reader = new FileReader("c:/Disks/text.txt");
            bufferedReader  = new BufferedReader(reader);

            //3. Call the BufferedReader object readLine() method to read the file
            String s = null;
            while ((s = bufferedReader.readLine())!= null){
                System.out.println(s);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Close the input stream
            try {
                bufferedReader.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Writer class

  • Character output stream

    Writer-OutputStreamWriter-FileWriter-BufferedWriter

    write()

  • Common methods:

    Method nameexplain
    int writer(String str)
    int writer(String str,int off,int len)
    void close()
    void flush()

FileWriter: grandchild

Construction method:

  • FileWriter(File file)
  • FileWriter(String name)
  • Generation and construction method with boolean type

Reading steps:

  1. Introduce resources (related classes)
  2. Create FileWriter object
  3. Read the file with the help of the write() method of the FileWriter object
  4. Close input stream
import java.io.*;
//Write content to the file with the help of the character input stream FileWriter
public class FileWriterDemo {
    public static void main(String[] args) throws IOException {
        System.out.println(System.getProperty("file.encoding"));
        Writer writer = null;
        writer = new FileWriter("c:/Disks/text.txt");
        String s = "hello writer,Character output stream";
        writer.write(s);
        writer.close();
    }
}

Chinese garbled Code: OutputStreamWriter

  • It can only be written in local coding format
import java.io.*;

//Write content to the file with the help of character input stream OutputStreamWriter -- solving the problem of Chinese garbled code
public class OutputStreamWriterDemo {
    public static void main(String[] args) throws IOException {
        System.out.println(System.getProperty("file.encoding"));
        Writer writer = null;
        FileOutputStream fileOutputStream = new FileOutputStream("c:/Disks/text.txt");
        //Character output stream, a byte output stream is packaged, and the character coding format is specified at the same time
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"UTF-8");
        String s = "hello writer,Character output stream 111";
        outputStreamWriter.write(s);
        outputStreamWriter.close();
        fileOutputStream.close();
    }
}

BufferedWriter class: subclass

  • With buffer
  • newLine(): open a new line
import java.io.*;

//With the help of the character input stream BufferedWriter, write the content buffer to the file to improve efficiency
public class BufferedWriterDemo {
    public static void main(String[] args) throws IOException {
        System.out.println(System.getProperty("file.encoding"));
        Writer writer = null;
        FileOutputStream fileOutputStream = new FileOutputStream("c:/Disks/text.txt");
        //Character output stream, a byte output stream is packaged, and the character coding format is specified at the same time
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"UTF-8");
        //Character output stream with buffer
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

        bufferedWriter.write("First line content");
        bufferedWriter.newLine();//Line feed
        bufferedWriter.write("Second line content");
        bufferedWriter.newLine();
        bufferedWriter.write("Content of the third line");
        bufferedWriter.flush();

        outputStreamWriter.close();
        fileOutputStream.close();
        bufferedWriter.close();
    }
}

Comprehensive practice of character input and output stream

import java.io.*;

public class ReaderAndWriter {
    public static void main(String[] args) throws FileNotFoundException {
        //Read file pet template
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        //Use the character output stream with buffer to write the replaced new content to pet Txt
        BufferedWriter bufferedWriter = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
             inputStreamReader =
                    new InputStreamReader(new FileInputStream("c:/Disks/pet.template"),"UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);

            StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line=bufferedReader.readLine()) != null){
                stringBuffer.append(line);
            }
            System.out.println("Before replacement:"+stringBuffer);

            //Replace the contents of the file by replacing the placeholder with specific information
            String newStr = stringBuffer.toString();
            newStr = newStr.replace("{name}","Roar");
            newStr = newStr.replace("{type}","Border grazing");
            newStr = newStr.replace("{master}","Zhang San");
            System.out.println("After replacement:"+newStr);

            //Write new content to pet Txt file
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream("c:/Source/pet.txt"),"UTF-8");
            bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(newStr);
            bufferedWriter.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            try {
                bufferedReader.close();
                inputStreamReader.close();
                bufferedWriter.close();
                outputStreamWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

Reading and writing binary files

  • Pictures and video files are binary files in the computer

DataInputStream

  • Subclass of FileInputStream
  • Use with FileInputStream class to read binary files

DataOutputStream

  • Subclass of FileOutputStream
  • Use with FileOutputStream class to write binary files
import java.io.*;
//Reading and writing binary files with DataInputStream and DateOutputStream
public class CopyPic {
    public static void main(String[] args) throws IOException {
        //Read picture file C: / coder jpg
        DataInputStream dataInputStream = null;
        FileInputStream fileInputStream = null;

        //Write the picture file to D: / disks / mycoder jpg
        DataOutputStream dataOutputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //Input stream
            fileInputStream = new FileInputStream("c:/coder.jpg");
            dataInputStream = new DataInputStream(fileInputStream);
            //Output stream
            fileOutputStream = new FileOutputStream("c:/Disks/myCoder.jpg");
            dataOutputStream = new DataOutputStream(fileOutputStream);
            int temp;
            while ((temp = dataInputStream.read()) != -1){
                dataOutputStream.write(temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            dataOutputStream.close();
            fileOutputStream.close();
            dataInputStream.close();
            fileInputStream.close();
        }
    }
}

serialize

  • ObjectOutputStream implements object serialization
  • Serialization is the process of writing the state of an object to a specific stream

Object output stream: ObjectOutputStream

  • It is used in combination with FileOutputStream to realize the serialization of objects

Steps for serialization:

  1. Implement Serializable interface
  2. Create object output stream
  3. Call the writeObject() method to write the object to a file
  4. Close object output stream
import java.io.Serializable;

public class Student implements Serializable {
    private int age;
    private String name;
    private String sex;
    private String password;

    public Student() {
    }

    public Student(int age, String name, String sex, String password) {
        this.age = age;
        this.name = name;
        this.sex = sex;
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

import java.io.*;

//Serialize college object
public class SeriaStu {
    public static void main(String[] args) {
        Student student = new Student(18,"Anna","female","123456");

        //Object output stream
        ObjectOutputStream objectOutputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
             //Build an object output stream to prepare for serialization
            fileOutputStream = new FileOutputStream("c:/Disks/student.txt");
            objectOutputStream = new ObjectOutputStream(fileOutputStream);

            //Implement object serialization
            objectOutputStream.writeObject(student);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                objectOutputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

The object type must implement the Serializable interface

Deserialization

  • ObjectInputStream

  • Deserialization is the process of retrieving data from a specific stream and reconstructing objects

Object input stream: ObjectInputStream

  • Used in combination with FileInputStream to realize the deserialization of objects
  • readObject()

Steps for serialization:

  1. Implement Serializable interface
  2. Create object input stream
  3. Call the readObject() method to read out the object of the file
  4. Close object input stream
import java.io.*;

//Serializing and deserializing objects
public class SeriaStu {
    public static void main(String[] args) {
        Student student = new Student(18,"Anna","female","123456");

        //Object input stream
        ObjectInputStream objectInputStream = null;
        FileInputStream fileInputStream = null;

        try {

            //Build the object output and input stream to prepare for anti serialization
            fileInputStream = new FileInputStream("c:/Disks/student.txt");
            objectInputStream = new ObjectInputStream(fileInputStream);
            
            //Implement object deserialization
            Student student1 = (Student)objectInputStream.readObject();
            System.out.println("Deserialized student information:"+student1.getName()+"-"+student1.getAge()+"-"+student1.getSex()+"-"+student1.getPassword());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                objectInputStream.close();
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

transient:

  • Implement a property of an object to avoid serialization or deserialization

Keywords: Java

Added by bigrollerdave on Sat, 05 Mar 2022 04:17:04 +0200