JAVA programming basic study notes - input and output stream (MOOC) note arrangement | Final exam preparation | Text file writing and reading | Binary file writing and reading | File class introduction

This chapter will introduce the following parts in turn

Table of contents

The concept of input and output streams

Predefined I/O stream classes

Divide from the direction of flow

From the division of streams

Divide from the content of the stream

Writing and reading text files

Text file writing

Reading of text files

Writing and reading binary files

writing binary files

Reading of binary files

Introduction to the File class

object serialization

ObjectInputStream object input stream

ObjectOutputStream object output stream

homework


The concept of input and output streams

In Java, both input and output are abstracted as a flow of information

Input stream: information flows into the program space from other places outside the program space

Output stream: send data in the program space to other places outside the program space

Predefined I/O stream classes

Divide from the direction of flow

input stream

output stream

From the division of streams

Node stream: the stream that actually accesses files and performs input and output operations

Processing flow: On the basis of node flow, the flow of processing and converting information

Divide from the content of the stream

Top-level hierarchy of java.io packages

Character-oriented streams: specifically for character data

  • The source or target is usually a text file
  • Implement conversion between internal formats and external formats in text files
    • Internal format: 16-bit char data type
    • External format:
      • UTF (Universal character set Transformation Format): Many people call it "Universal Text Format".
      • Including ASCII and non-ASCII characters, such as: Cyrillic characters, Greek characters, Asian characters, etc.

Character-oriented abstract stream class - Reader and Writer

  • Abstract superclass for all character streams in the java.io package
  • Reader provides an API for inputting characters
  • Writer provides an API for outputting characters
  • Their subclasses can be divided into two categories
    • Node flow: read data from the data source or write data to the destination;
    • Process flow: perform some kind of processing on the data
  • Most programs use a series of subclasses of these two abstract classes to read/write textual information
    • For example FileReader / FileWriter is used to read/write text files

The figure above lists some character-oriented streams, where the shaded part is the node stream, and the others are the processing streams 

Byte-oriented streams: for general-purpose input and output

It is used to process the input and output of non-text data. Most of the data is not text data, such as some images, sounds, videos, etc.

Even if some data can be stored as both text and binary, it saves a lot of space when we store these data as binary, and we send data from memory to other places other than memory, such as files In the middle, if it is stored in binary form, it will save time. So sometimes, if the data we want to store is not intended to be read by humans, but to be processed by other programs, then try to store the data in binary, so that during the storage process or the output process It will save time and save space on storage media

Byte-oriented abstract stream classes - InputStream and OutputStream

  • It is an abstract base class for processing byte streams, and programs use subclasses of these two classes to read and write byte information.
  • divided into two parts
    • node flow
    • processing flow

standard input and output stream object

  • Static member variables of the System class
  • include
    • System.in: InputStream type, representing the standard input stream, the default state corresponds to keyboard input.
    • System.out: PrintStream type, representing the standard output stream, the default state corresponds to the display output.
    • System.err: PrintStream type, representing the standard error information output stream, the default state corresponds to the display output.

Writing and reading text files

Text file writing

How to create a text file and write information to the text file?

Look at the code below

package Week13.com.videolearn;

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

//创建文件并写入若干行文本
public class FileWriterTester {
    public static void main(String[] args) throws IOException {

        //main方法中声明抛出IO异常
        String fileName = "Hello.txt";
        FileWriter writer = new FileWriter(fileName);
        writer.write("Hello!\n");
        writer.write("This is my first text file,\n");
        writer.write("You can see how this is done.\n");
        writer.write("输入一行中文也可以\n");
        writer.close();
    }
}

//每次运行都会删除旧文件生成新文件
//换行在不同平台可能会有不同效果
/*
注意在该代码中:
1.用“\n”作为回车,会产生小黑格
2.没有对异常进行处理,仅仅抛出
3.没有实现追加方式写文件
* */

The result of the operation is as follows:

We continue to modify the code

package Week13.com.videolearn;

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

public class FileWriterTester02 {
    public static void main(String[] args) {

        String fileName = "Hello.txt";

        try {//将所有IO操作放入try块中
            //true参数表示是追加
            FileWriter writer = new FileWriter(fileName, true);
            writer.write("Hello!\n");
            writer.write("This is my first text file,\n");
            writer.write("You can see how this is done.\n");
            writer.write("输入一行中文也可以\n");
            writer.close();
        } catch (IOException e) {
            System.out.println("Problem writing" + fileName);
        }
    }
}

/*
* 说明:
运行此程序,会发现在原文件内容后面又追加了重复的内容,
* 这就是将构造方法的第二个参数设为true的效果。
* 如果将文件属性改为只读属性,再运行本程序,就会出现IO错误,
* 程序将转入catch块中,给出出错信息。
*
*
*
* 如果我们要写入文件中的信息比较多,那么写的效率就是个问题
* 这时候我们可以用BufferedWriter类进行缓冲,能够提高写的效率
*
* 
* */

The result of the operation is as follows:

BufferedWriter class

  • Both the FileWriter and BufferedWriter classes are used to output character streams, and the methods they contain are almost identical, but BufferedWriter provides an additional newLine() method for line breaks. This line break effect is cross-platform.
  • Different systems wrap text differently. The newLine0 method can output the correct newline character on the current computer.

The following code demonstrates writing files using BufferedWriter

package Week13.com.videolearn;

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

public class BufferedWriterTester {
    public static void main(String[] args) throws IOException {

        String fileName = "newHello.txt";
        BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
        out.write("Hello!");
        out.newLine();//换行,可以跨平台
        out.write("This is another text file using BufferedWriter,");
        out.newLine();
        out.write("So I can use a common way to start a newline");
        out.close();
    }
}

The result of the operation is as follows:

Reading of text files

Classes related to reading text files

  • FileReader class
    • read characters from text file
    • Inherited from the subclass InputStreamReader of the Reader abstract class
  • BufferedReader class
    • Buffer class for reading text files
    • It has the readLine0 method, which can identify newline characters and read the contents of the input stream line by line.
    • Inherited from Reader.
package Week13.com.videolearn;

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

//读文本文件并显示
public class BufferedReaderTester {
    public static void main(String[] args) {

        String fileName = "Hello.txt", line;

        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
            line = bufferedReader.readLine();       //读取一行的内容
            while(line != null) {
                System.out.println(line);
                line = bufferedReader.readLine();
            }
            bufferedReader.close();
        } catch (IOException e) {

            System.out.println("Problem reading" + fileName);
        }

    }
}

/*
* 运行该程序,屏幕上将逐行显示出Hello.txt文件中的内容。
* FileReader对象:创建后将打开文件,如果文件不存在,会抛出一个IOException
* BufferedReader类的readLine()方法:从一个面向字符的输入流中读取一行文本。如果其中
* 不再有数据,返回null
Reader类的read()方法:也可用来判别文件结束。该方法返回的一个表示某个字符的int型整数,
* 如果读到文件末尾,返回 -1。据此,可修改本例中的读文件部分:
int c
* while((c = in.read())!= -1)
* System.out.print((char)c);
* close()方法:为了操作系统可以更为有效地利用有限的资源,应该在读取完毕后,调用该方收
*
*
* 思考:如何实现文本文件的复制呢?
* */

The result of the operation is as follows:

Writing and reading binary files

writing binary files

Abstract class OutputStream

  • Derived class FileOutputStream
    • For general purpose output (non-character output);
    • For grouped byte output.
  • Derived class DataOutputStream
    • Has methods for writing various basic data types;
    • write data to another output stream;
    • It uses the same data format on all computer platforms;
    • Among them, the size method can be used as a counter to count the number of bytes written.

For example, to write int data into a binary file, the code is as follows:

package Week13.com.videolearn;

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

//将三个int型数字255/0/-1写入数据文件data1.dat
public class FileOutputStreamTester {
    public static void main(String[] args) {

        String filename = "data1.dat";
        int value0 = 255, value1 = 0, value2 = -1;
        try {
            //FileOutputStream是源生字节流,只识别写出去的是一个一个字节
            //没办法识别数据类型,DataOutputStream是处理流,可以将字节首先处理成某种
            //类型的数据
            DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(filename));
            dataOutputStream.writeInt(value0);
            dataOutputStream.writeInt(value1);
            dataOutputStream.writeInt(value2);
            dataOutputStream.close();
        } catch (IOException e) {

            System.out.println("Problem writing" + filename);
        }

    }
}

/*
* 运行结果
运行程序后,生成数据文件datal.dat
用写字板打开没有任何显示
用ultraEdit打开查看其二进制信息,内容为00.00 00 FF 00 0000 00 FF FF FF FF,
* 每个int数字都是32个bit的
说明
FileOutputStream类的构造方法负责打开文件“data1.dat”用于写数据
* FileOutputStream类的对象与DataOutputStream对象连接,写基本类型的数据
*
* 当需要写大量数据时,用缓冲流类可以提高写的效率
*
*
* */

Let's look at the buffer stream class

BufferedOutputStream class

  • Usage example:
    • DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
    • BufferedOutputStream is also a processing stream, it is buffered, but not directly written

Write a variety of data to the file and count the number of bytes. The code is as follows:

package Week13.com.videolearn;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

//向文件写入多种数据,统计字节数
public class BufferedOutputStreamTester {
    public static void main(String[] args) throws IOException {

        String fileName = "mixedTypes.dat";
        //首先构造输出流对象
        //在源生字节输出流对象基础上构造一个缓冲的BufferedOutputStream,提高写的效率
        //DataOutputStream可以按照类型去写二进制数据
        DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
        dataOutputStream.writeInt(0);
        System.out.println(dataOutputStream.size() + "bytes have been written");
        dataOutputStream.writeDouble(31.2);
        System.out.println(dataOutputStream.size() + "bytes have been written");
        dataOutputStream.writeBytes("JAVA");
        System.out.println(dataOutputStream.size() + "bytes have been written");
        dataOutputStream.close();
    }
}

The result of the operation is as follows:

  

Reading of binary files

previously written data to the file in binary

Read and add three int numbers in the binary file, the code is as follows:

package Week13.com.videolearn;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

//读取二进制文件中的三个int型数字并相加
public class DataInputStreamTester {
    public static void main(String[] args) {

        String fileName = "data1.dat";
        int sum = 0;
        try {
            //首先构造输入流对象FileInputStream(源生字节的输入流)
            //BufferedInputStream缓冲流
            //DataInputStream可以按类型读取
            DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
            //问题1:当初这个文件写的是什么类型的数据要知道,不然就没办法了
            //问题2:如果不知道这个文件中总共有多少个整数,怎么判断?
            //可以依赖异常,捕获DataInputStream的文件结束异常
            sum += dataInputStream.readInt();
            sum += dataInputStream.readInt();
            sum += dataInputStream.readInt();
            System.out.println("The sum is:" + sum);
            dataInputStream.close();
        } catch (IOException e) {
            System.out.println("Problem reading" + fileName);
        }

    }
}

The result of the operation is as follows:

 

Copy files by reading and writing bytes, regardless of whether the file is a binary file or a text file, it can be implemented

What if any type of file needs to be copied?

code show as below:

package Week13.com.videolearn;

import java.io.*;

//从命令行输入源文件名和目标文件名,将源文件复制为目标文件
public class CopyBytes {
    public static void main(String[] args) {

        DataInputStream instr;
        DataOutputStream outstr;
        if(args.length != 2) {
            System.out.println("Please enter file names");
            return;
        }
        try {
            instr = new DataInputStream(new BufferedInputStream(new FileInputStream(args[0])));
            outstr = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(args[1])));

            try {
                int data;
                while(true) {
                    data = instr.readUnsignedByte();
                    outstr.writeByte(data);
                }
            } catch (EOFException e) {
                //遇到文件尾,会抛出文件结束异常,捕获
                outstr.close();
                instr.close();
                return;
            }
        } catch (FileNotFoundException nfx) {
            System.out.println("Problem opening files");
        } catch (IOException iox) {
            System.out.println("IO Problems");
        }
    }
}

Introduction to the File class

String Filename in the program for reading and writing files can be replaced by File object

Note: The File class in Java is only used to operate files and obtain file information; file data reading is provided by file streams

The role of the File class

  • Create and delete files;
  • rename the file;
  • Determine the read and write permissions of the file and whether it exists;
  • Set and query the last modification time of files, etc.;
  • Constructing a file stream can use an object of the File class as a parameter

Next look: Combining the File class to improve the previous binary file copy program

Several commonly used methods of the File class (see Example 7-6 on page P194):

  • isFile0 method to determine whether a File object represents a file
  • isDirectory0 method to determine whether the File object represents a directory
  • The exists0 method determines whether a file or path with the same name exists

The improved file copy program code is as follows:

package Week13.com.videolearn;

import java.io.*;

//改进的文件复制程序
public class NewCopyBytes {
    public static void main(String[] args) {

        DataInputStream instr;
        DataOutputStream outstr;

        if(args.length != 2) {
            System.out.println("Please Enter file names!");
            return;
        }
        File inFile = new File(args[0]);
        File outFile = new File(args[1]);
        //exists方法判断要打开的文件是否存在
        if(outFile.exists()) {
            System.out.println(args[1] + " already exists");
            return;
        }
        if(! inFile.exists()) {
            System.out.println(args[0] + "does not exist");
            return;
        }

        try {
            instr = new DataInputStream(new BufferedInputStream(new FileInputStream(inFile)));
            outstr = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));

            try {
                int data;
                while(true) {
                    data = instr.readUnsignedByte();
                    outstr.writeByte(data);
                }
            } catch (EOFException e) {
                outstr.close();
                instr.close();
                return;
            }
        } catch (FileNotFoundException nfx) {
            System.out.println("Problem opening files");
        } catch (IOException iox) {
            System.out.println("IO Problems");
        }
    }
}

object serialization

How long can our objects in program memory survive?

Its longest lifespan is when the program ends, the occupied space will be released, and the objects in the memory will no longer exist. If the information in some objects needs to be kept permanently, it will be saved at this time. To serialize the object, that is to say, write the object to the file as a whole, and then read it out as a whole.

ObjectInputStream/ObjectOutputStream类

Implement object reading and writing

ObjectInputStream object input stream

Write objects to disk files through ObjectOutputStream

ObjectOutputStream object output stream

Read objects into the program through ObjectInputStream

Variables of transient and static types that do not save objects

In order for an object to be serialized, its class must implement the Serializable interface

ObjectOutputStream (processing stream)

ObjectOutputStream must be constructed from another stream:

FileOutputStream out = new FileOutputStream("theTime");

ObjectOutputStream s = new ObjectOutputStream(out);

s.writeObject("Today");//The parameters here have already implemented the Serializable interface

s.writeObject(new Date());//The parameters here have already implemented the Serializable interface

s.flush();//Empty the buffer

ObjectInputStream (processing stream)

ObjectInputStream must be constructed from another stream:

FileInputStream in = new FileInputStream("theTime");

ObjectInputStream s = new ObjectInputStream(in):

String today = (String)s.readObject();

Date date = (Date)s.readObject0);

If the objects we define also need to be read from the entire file, then our class must implement the Serializable interface, which is actually an empty interface.

Seriealizable

  • Definition of the Serializable interface

package java.io;

public interface Serializable {

        // there's nothing in here!
}

  • Statements that implement the Serializable interface

public class MyClass implements Serializable {

...

}

  • Use the keyword transient to prevent certain members of the object from being automatically written to the file
  • In fact, this is a flag. When designing this class, it is intended to allow the object to be written to disk in its entirety.

homework

Please practice Example 7-10 on page P203 of the textbook

Save the Employee object (can be modified on the previously practiced Employee definition)

Guess you like

Origin blog.csdn.net/Raider1/article/details/130690938