Introduction to IO
1 Stream Stream
Before learning IO stream, the first concept we need to learn is Stream stream
In order to facilitate understanding, we can abstract the read and write operations of data into the flow of data in a "pipe", but pay attention to:
1. Flow can only flow in one direction
2. The input stream is used to read → in
3. The output stream is used to write out → out
4. Data can only be read and written once from the beginning to the end
So think from the point of view of the program, In/out is the process of input (reading)/output (writing out) relative to the program.
2 Inheritance structure of IO stream
In java, streams can be divided into byte streams and character streams according to the data units processed.
byte stream : for binary files
Character stream: for text files
Combined with the input and output directions of the corresponding type, the commonly used streams are:
File
byte stream: for binary files
InputStream
FileInputStream
BufferedInputStream
ObjectInputStream
OutputStream
FileOutputStream
BufferedOutputStream
ObjectOutputStream
Character stream: for text files
Reader
FileReader
BufferedReader
InputStreamReader
Writer
FileWriter
BufferedWriter
OutputStreamWriter
PrintWriter writes out line by line
3 File file class
3.1 Overview
Encapsulates a disk path string that can perform an operation on this path
Can encapsulate file path, folder path, non-existent path
3.2 Creating objects
File(String pathname) creates a new File instance by converting the given pathname string to an abstract pathname
new File("d:/abc/a.txt");
new File("d:/abc","a.txt");
3.3 Common methods
3.4 Exercise: test common methods
Create package: cn.tedu.file
Create class: TestFile.java
package cn.tedu.file; import java.io.File; import java.io.IOException; import java.util.Arrays; /*This class is used to test the file class File*/ public class TestFile { public static void main(String[] args) throws IOException { //1. Create a File class object /*1.ready The directory and 1.txt need to be manually created by yourself * 2.File Need to import package: import java.io.File; * 3.The path is of type String and must be written correctly, otherwise the file cannot be found * 4.The complete file name consists of two parts: file name + suffix name*/ File file = new File("E:\\ready\\1.txt"); //2.1 Test common methods in File System.out.println(file.length());//3. Get the bytes of the file System.out.println(file.exists());//true, to determine whether the file exists System.out.println(file.isFile());//true, to determine whether it is a file System.out.println(file.isDirectory());//false, to determine whether it is a folder System.out.println(file.getName());//1.txt to get the file name System.out.println(file.getParent());//E:\ready get parent path System.out.println(file.getAbsolutePath());//E:\ready\1.txt Get the full path with drive letter: absolute path //2.2 Test creation and deletion /*new It will only help you create an object of type File in memory * won't help you create a real 2.txt file on disk*/ file = new File("E:\\ready\\2.txt"); //Create a file 2.txt that did not exist before, if the creation is successful, it will return true /*If the specified path to create the file is incorrect, an exception will be thrown: java.io.Exception * So we need to deal with this problem in advance, we temporarily choose to throw on main() * This IO exception is the exception we are currently encountering that must be handled in advance * If it is not processed, the method call will report an error, and the compilation will not pass.*/ System.out.println(file.createNewFile());//Create a file that didn't exist before file = new File("E:\\ready\\m"); System.out.println(file.mkdir());//Create a single-level folder that didn't exist before file = new File("E:\\ready\\a\\b\\c"); System.out.println(file.mkdirs());//Create multi-level folders that didn't exist before System.out.println(file.delete());//c is deleted, delete empty folders or files file = new File("E:\\ready\\a"); System.out.println(file.delete());//false,a folder is not empty, there is content in it file = new File("E:\\ready\\2.txt"); System.out.println(file.delete());//2.txt is deleted, you can delete the file //2.3 Test display file list file = new File("E:\\ready"); String[] list = file.list();/*uncommonly used*/ System.out.println(Arrays.toString(list)); //This sentence will report an error, because this is a String[], so each element in the array is of type String //Then you can only use the methods in the String class, and isDirectory() is the method in the File class //System.out.println(list[0].isDirectory()); File[] fs = file.listFiles();/*Commonly used*/ System.out.println(Arrays.toString(fs)); System.out.println(fs[0].isDirectory()); } }
4 byte stream read
Byte streams are composed of bytes, and character streams are composed of characters.
Characters in Java consist of two bytes. Byte streams are elementary streams and are mainly used to process binary data.
So byte streams are more commonly used, and can handle a variety of different types of files, such as text documents/audio/video, etc.
4.1 InputStream abstract class
This abstract class is the superclass/abstract class of all classes that represent byte input streams. Objects cannot be created.
Common method:
abstract int read() reads the next byte of data from the input stream
int read(byte[] b) reads a certain number of bytes from the input stream and stores them in the buffer array b
int read(byte[] b, int off, int len) Reads up to len data bytes in the input stream into the byte array, off represents the offset when stored
void close() closes this input stream and releases all system resources associated with this stream
4.2 FileInputStream subclasses
Insert directly on the file, read the file data directly
create object
FileInputStream(File file)—directly transfer the file object
Creates a FileInputStream by opening a connection to the actual file specified by the File object file in the file system FileInputStream(String pathname)—passing the path
Creates a FileInputStream by opening a connection to the actual file specified by the pathname name in the filesystem
4.3 BufferedInputStream subclasses
BufferedInputStream adds some functionality to another input stream, when a BufferedInputStream is created, an internal buffer array (default 8k size) is created. This internal buffer can be refilled as needed from the containing input stream, multiple bytes at a time, as bytes in the stream are read or skipped.
create object
BufferedInputStream(InputStream in)
Create a BufferedInputStream and save its parameter, the input stream in, for future use.
4.4 Exercise: Byte Stream Read Case
Create package: cn.tedu.file
Create class: TestIn.java
package cn.tedu.file; import java.io.*; /*This class is used to practice byte input streams*/ public class TestIn { public static void main(String[] args) { //method();//Read byte stream method2();//Efficient byte stream reading } //This method is used to test the reading of efficient byte streams private static void method2() { //Define a local variable in that takes effect in this method, pay attention to manual initialization, the value is null InputStream in = null; try { //1. Create an efficient byte input stream object // InputStream in = new BufferedInputStream( // new FileInputStream(new File("E:\\ready\\1.txt"))); in = new BufferedInputStream (new FileInputStream("E:\\ready\\1.txt")); //2. Read using streams int b; while ((b= in.read())!= -1){ System.out.println(b); } } catch (Exception e) { e.printStackTrace(); }finally {//The closing operation is written in finally{} //3. Be sure to close the stream after it is used up! ! ! try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } //This method is used to test the read of the byte stream private static void method() { //Create a local variable that takes effect in this method, pay attention to manual initialization InputStream in = null; try { //1. Create a byte input stream object for reading //InputStream in = new InputStream();//Reason for error: abstract class cannot be instantiated //InputStream in = new FileInputStream(new File("E:\\ready\\1.txt")); in = new FileInputStream("E:\\ready\\1.txt"); //2. Start reading /*read()Each call will read a byte, if the end of the data is read, return -1*/ // System.out.println(in.read()); // System.out.println(in.read()); // System.out.println(in.read()); // System.out.println(in.read()); //Requirement: You need to read all the content in the file in a loop until it is finished //Define variables to record the data read int b; while((b=in.read())!= -1){ System.out.println(b); } } catch (Exception e) { e.printStackTrace();//print error message /*try-catch The third part in the structure: finally{} * This part is the code that will be executed regardless of whether an exception is caught or not, and is often used to close the stream.*/ }finally { try { //3. Release the resources, the stream resources must be released when they are used up! ! ! in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
5 character stream read
It is often used to process plain text data, and reading and writing is prone to garbled characters. When reading and writing, it is best to specify the encoding set as UTF-8.
5.1 Reader abstract class
Abstract class for reading character streams.
Common method:
int read() reads a single character
int read(char[] cbuf) reads characters into an array
abstract int read(char[] cbuf, int off, int len) read characters into a part of an array
int read(CharBuffer target) attempts to read characters into the specified character buffer
abstract void close() closes the stream and releases all resources associated with it
5.2 FileReader subclasses
Convenience class for reading character files. The constructor of this class assumes that both the default character encoding and the default byte buffer size are appropriate. To specify these values yourself, you can first construct an InputStreamReader on the FileInputStream.
create object
FileReader(String fileName) creates a new FileReader given the filename to read data from
FileReader(File file) creates a new FileReader given the File to read data from
5.3 BufferedReader subclasses
Reads text from a character input stream, buffering individual characters for efficient reading of characters, arrays, and lines.
The size of the buffer can be specified, or the default size can be used. In most cases, the default value is large enough.
create object
BufferedReader(Reader in) creates a buffered character input stream using the default size input buffer
5.4 Exercise: Character Stream Reading Example
Create package: cn.tedu.file
Create class: TestIn2.java
package cn.tedu.file; import java.io.*; /*This class is used to test the reading of character streams*/ public class TestIn2 { public static void main(String[] args) { //method();//Test the normal character input stream method2();//Test efficient character input streams } //Create a method for testing efficient character input streams private static void method2() { //1. Define a local variable that takes effect in this method, and manually initialize the value null Reader in=null; try{ //1. Create an efficient character read stream object //in = new BufferedReader(new FileReader(new File("E:\\ready\\1.txt"))); in = new BufferedReader(new FileReader("E:\\ready\\1.txt")); //2. Using stream objects int b; while((b=in.read())!=-1){ System.out.println(b); } }catch (Exception e){ e.printStackTrace(); }finally { //3. Close the stream object try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } //Create a method for testing a normal character input stream private static void method() { //1.1 Create a local variable that takes effect in this method, pay attention to the initialization value null Reader in = null; try { //1.2 Create a character input stream object, pay attention to the need to catch exceptions //Reader in = new Reader();//Reason for error: abstract parent cannot be instantiated //in = new FileReader(new File("E:\\ready\\1.txt")); in = new FileReader("E:\\ready\\1.txt"); //2. Using stream objects //System.out.println(in.read()); //Requirement: Read all the contents of the file in a loop, as long as it is not -1, it means that there is still data, continue to read //3.1 Define variables and record the read data int b; while((b = in.read())!= -1){ System.out.println(b); } } catch (Exception e) { e.printStackTrace(); } finally {//3. Turn off the flow try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
6 byte stream write out
6.1 OutputStream abstract class
This abstract class is the superclass of all classes that represent a stream of output bytes. An output stream accepts output bytes and sends those bytes to some receiver.
Common method:
Void close() closes this output stream and releases all system resources associated with this stream
Void flush() flushes this output stream and forces all buffered output bytes to be written out
Void write(byte[ ] b) writes b.length bytes from the specified byte array to this output stream
Void write(byte[ ] b,int off ,int len) Writes len bytes from offset off in the specified byte array to the output stream
Abstract void write(int b) writes the specified bytes to this output stream
6.2 FileOutputStream subclasses
Insert directly on the file, write out the file data directly
Constructor (create object):
FileOutputStream(String name)
Creates a file output stream that writes data to a file with the specified name
FileOutStream(File file)
Creates a file output stream that writes data to the file represented by the specified File object
FileOutStream(File file,boolean append) - if the second parameter is true, it means appending, not overwriting
Create a file output stream that writes data to the file represented by the specified File object. The following parameters refer to whether to overwrite the original file content
6.3 BufferedOutputstream subclasses
This class implements a buffered output stream. By setting this output stream, the application can write each byte into the underlying output stream without calling the underlying system every time the byte is written out.
Constructor (create object):
BufferedOutputStream(OutputStream out)
Creates a new buffered output stream for writing data to the specified underlying output stream
6.4 Exercise: Byte Output Stream Test:
Create package: cn.tedu.file
Create class: TestOut.java
package cn.tedu.file; import java.io.*; /*This class is used to test byte output streams*/ public class TestOut { public static void main(String[] args) { method();//For testing plain byte output streams //method2();//For testing efficient byte output stream } //Create a method for testing an efficient byte output stream private static void method2() { //1. Create a local variable that takes effect in this method, pay attention to manual initialization OutputStream out = null; try{ //2. Create an efficient byte output stream object // out = new BufferedOutputStream(new FileOutputStream(new File("E:\\ready\\2.txt"))); out = new BufferedOutputStream(new FileOutputStream("E:\\ready\\2.txt")); //3. Use stream objects -- write out operations out.write(97); out.write(97); out.write(97); }catch (Exception e){ e.printStackTrace(); }finally {//The closing operation should be placed in finally{} try { //4. Turn off the flow out.close(); } catch (IOException e) { e.printStackTrace(); } } } //Create a method for testing a normal byte output stream private static void method() { //1. Create a local variable that takes effect in this method, pay attention to manually initialize null OutputStream out = null; //2. Create a try-catch-finally structure, because IO operations may generate exceptions try{ //3. Create a normal byte output stream object //out = new FileOutputStream(new File("E:\\ready\\2.txt")); //out = new FileOutputStream("E:\\ready\\2.txt"); out = new FileOutputStream("E:\\ready\\2.txt",true); //4. Use stream objects -- write out operations out.write(99);//Corresponds to a in the ASCII code table out.write(99);//Corresponds to b in the ASCII code table out.write(99);//Corresponds to c in the ASCII code table }catch (Exception e){ e.printStackTrace(); }finally {//If you want the code to be executed, you need to write it in finally try { //5. Shutdown operation out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
7 character stream write out
7.1 Writer abstract class
Abstract class for writing character streams
Common method:
Abstract void close() closes this stream, but flushes it first
Void write(char[ ] cbuf) writes a character array
Void write(int c) writes a single character
Void write(String str) writes a string
Void write(String str,int off,int len) writes a part of the string
Abstract void write(char[] cbuf,int off,int len) Write a part of the character array
7.2 FileWriter subclasses
Convenience class for writing character files. The constructor of this class assumes that the default character encoding and default byte buffer size are acceptable. If you need to customize these values yourself, you can first construct an OutputStreamWriter on the FileOutputStream.
Constructor (create object):
FileWriter(String filename)
Constructs a FileWriter object from the given filename
FileWriter(String filename,boolean append)
Constructs a FileWriter from the given filename and a boolean indicating whether to append write data
7.3 BufferedWriter subclasses
Writes text to a character output stream, buffering individual characters, providing efficient writing of individual characters, arrays, and strings. The size of the buffer can be specified, or the default size can be accepted, which is large enough in most cases span
Constructor (create object):
BufferedWriter(Writer out)
Creates a buffered character output stream that uses the default size output buffer
7.4 Exercise: Character Output Stream Test:
Create package: cn.tedu.file
Create a class: TestOut2.java
package cn.tedu.file; import java.io.*; /*This class is used to test character output streams*/ public class TestOut2 { public static void main(String[] args) { //method();//Used to test the normal character output stream method2();//For testing efficient character output streams } //Create a method for testing efficient character output streams private static void method2() { //1. Create a local variable that takes effect in this method, the value is null, pay attention to manual initialization! ! ! Writer out = null; //2. Since the program may throw exceptions, you need to write a try-catch-finally structure try{//Store code that may throw exceptions //3. Create a normal character output stream object //out = new BufferedWriter(new FileWriter(new File("E:\\ready\\2.txt"))); //out = new BufferedWriter(new FileWriter("E:\\ready\\2.txt")); out = new BufferedWriter(new FileWriter("E:\\ready\\2.txt",true)); //4. Using Stream Objects out.write(100); out.write(100); out.write(100); out.write(100); out.write(100); }catch (Exception e){//match and catch exception e.printStackTrace();//Print an error message if an exception is caught }finally {//A code block that must be executed, often used to close the stream try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } //Create a method for testing the normal character output stream private static void method() { //1. Create a local variable that takes effect in this method, the value is null, pay attention to manual initialization! ! ! Writer out = null; //2. Since the program may throw exceptions, you need to write a try-catch-finally structure try{//Store code that may throw exceptions //3. Create a normal character output stream object //out = new FileWriter(new File("E:\\ready\\2.txt")); //out = new FileWriter("E:\\ready\\2.txt"); out = new FileWriter("E:\\ready\\2.txt",true); //4. Using Stream Objects out.write(98); out.write(98); out.write(98); out.write(98); }catch (Exception e){//match and catch exception e.printStackTrace();//Print an error message if an exception is caught }finally {//A code block that must be executed, often used to close the stream try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
8 Expand
By learning the above streams, we can also expand and try to copy files:
Create package: cn.tedu.file
Create class: TestCopyFile.java
package cn.tedu.file; import java.io.*; import java.util.Scanner; /*This class is used to practice the comprehensive case of file copying*/ public class TestCopyFile { public static void main(String[] args) { //1. Prompt and receive two paths for user input System.out.println("Please enter the source file path");//-- the file to be copied String f = new Scanner(System.in).nextLine(); System.out.println("Please enter the new file path:");//--Copy the new file String t = new Scanner(System.in).nextLine(); //2. Call the created custom method to complete the file copy //ZFCopy(f,t);//Complete file copy case with character stream ZJCopy(f,t);//Complete file copy case with byte stream } //Complete file copy case with byte stream private static void ZJCopy(String f, String t) { //1. Define local variables that take effect in the entire method, pay attention to manual initialization, the default value of reference type is null InputStream in = null; OutputStream out = null; //2. Since exceptions may occur in the code, you need to write a try-catch-finally structure try{ //3.1 Create an efficient byte input stream object--The parameter of FIS is the source file path f passed in by the user in = new BufferedInputStream(new FileInputStream(f)); //3.2 Create an efficient byte output stream object -- the parameter of FOS is the new file path t passed in by the user out = new BufferedOutputStream(new FileOutputStream(t)); //4. Use the created stream object to complete the business //4.1 Define variables to save the read data int b; //4.2 Read the data in the source file in a loop, as long as it is not -1, it means that there is still data looping to continue while((b = in.read()) != -1){ //4.3 Write the read data to a new file out.write(b); } System.out.println("congratulations! File copy successfully!"); }catch (Exception e){ System.out.println("terribly sorry! File copy failed!"); e.printStackTrace(); }finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } //Complete file copy case with character stream private static void ZFCopy(String f, String t) { //1. Define local variables that take effect in the entire method, pay attention to manual initialization, the default value is null Reader in = null; Writer out = null; //2. Since exceptions may occur in the code, you need to write a try-catch-finally structure try{ //3.1 Create efficient character input stream objects in = new BufferedReader(new FileReader(f)); //3.2 Create efficient character output stream objects out = new BufferedWriter(new FileWriter(t)); //4. After getting the stream object, you can use the stream object to complete the business //4.1 Define variables to save the read data int b; //4.2 Read the source file in a loop until the return value is -1, indicating that there is no data, and then end the loop while ((b=in.read())!=-1) { //4.3 Write the data read in this cycle to a new file out.write(b); } System.out.println("congratulations! File copy successfully!"); }catch (Exception e){ System.out.println("terribly sorry! File copy failed!"); e.printStackTrace(); }finally { /*Streams are closed sequentially: if there are multiple streams, the stream created last is closed first * Multiple shutdown statements require their own try-catch*/ try { out.close(); } catch (IOException e) { e.printStackTrace(); } try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
9 Summary: The inheritance structure of IO
1. Mainstream classification
1. Classify according to the direction: input stream output stream (relative to the program, writing data from the program to the file is the output)
2, according to the type of transmission: byte stream character stream
3. Combination: byte input stream byte output stream character input stream character output stream
2. Learning methods: learn common methods in abstract parent classes, and learn how to create objects in subclasses
3. Byte input stream:
InputStream abstract class, cannot be new, can be used as a superclass to learn the common methods it provides
--FileInputStream Subclass,Manipulate a file's byte input stream,common class --BufferedInputStream Subclass,buffered byte input stream,common class
4. Character input stream
Reader abstract class, not new, can be used as a superclass to learn the common methods it provides
--FileReader,Subclass,Manipulate the character input stream of a file,common class --BufferedReader,Subclass,buffered character input stream,common class
5. Byte output stream:
OutputStream abstract class, cannot be new, can be used as a superclass to learn the common methods it provides
--FileOutputStream Subclass,Manipulate the byte output stream of a file,common class --BufferedOutputStream Subclass,Buffered byte output stream,common class
6. Character output stream
Writer abstract class, cannot be new, can be used as a superclass to learn the common methods it provides
--FileWriter,Subclass,Manipulate the character output stream of a file,common class --BufferedWriter,Subclass,buffered character output stream,common class