file
File Stream
Files operate as streams in programs
flow
The path through which data travels between data sources (files) and programs (memory)
- Input stream: Path of data from data source (file) to program (memory)
- Output stream: Path of data from program (memory) to data source (file)
Common file operations
Create file object related constructors and methods
- new File(String path) Constructs a File object from a path
- New File (File parent, String child) is built from parent directory file + child path
- New File (String parent, String child) is built from parent directory + child path
- createNewFile Create New File
Get information about the file
- getName
- getAbsolutePath
- getParent
- length
- exists
- isFile
- isDirectory
Directory operations and file deletion
- mkdir creates a first-level directory
- mkdirs Create Multilevel Directory
- delete Delete an empty directory or file
IO Flow Principle and Classification
- I/O is the abbreviation of Input/Output. I/O technology is a very practical technology for data transmission. Read/write files, network communications, etc.
- In Java programs, input/output operations on data are performed as streams.
- Various "stream" classes and interfaces are provided under the java.io package to obtain different kinds of data and to input or output data through methods
- input: Reads external data (data from storage devices such as disks, discs) into programs (memory).
- output: output program (memory) data to disk, disc, and other storage devices
Classification of streams
-
Divided by unit of operational data
- Byte Stream (8 bit) Binary
- Character Stream (by Character) Text File
-
Divided by flow direction of data flow
- Input stream
- output stream
-
Divided by stream's role
- Node Flow
- Processing/Packaging Flow
Abstract Base Class | Byte Stream | Character Stream |
---|---|---|
Input stream | InputStream | Reader |
output stream | OutputStream | Writer |
- Java's IO stream covers more than 40 classes and is actually derived from the four abstract base classes above
- Subclass names derived from these four classes are suffixed by their parent name
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-NugZvRQy-1638116605258).) https://pumpkn.xyz/upload/2021/09/image-3230be943cab492ab2fd25378871d88c.png )]
InputStream:Byte Input Stream
InputStream abstract class is a superclass of all byte input streams
Common subclasses of InputStream
- FileInputStream File Input Stream
- BufferedInputStream Buffered Byte Input Stream
- ObjectInputStream Object Byte Input Stream
Use of FileInputStream
public class z1_FileInputStem { java.lang.String filePath = "D:\\z1.txt" ; /** * fileInputStream.read() * Read one byte at a time and block the method if the file is empty. * Return-1 if you read to the end of the file * */ @Test public void readFile(){ int readData ; try { FileInputStream fileInputStream = new FileInputStream(filePath); while( ( readData = fileInputStream.read() ) != -1 ){ System.out.print((char)readData); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Define a byte array * fileInputStream.read(bytes) * Read up to bytes of byte array length at a time, * Returns the number of bytes read * Return-1 at end of file * */ @Test public void readFileLength(){ byte[] bytes = new byte[8] ; int readLen ; try { FileInputStream fileInputStream = new FileInputStream(filePath); while( ( readLen = fileInputStream.read(bytes) ) != -1 ){ System.out.println(new java.lang.String(bytes , 0 , readLen)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Use of FileOutputStream
public class z2_FileOutputStem { @Test public void write(){ String filePath = "D:\\a.txt" ; FileOutputStream fileOutputStream = null ; try { //fileOutputStream = new FileOutputStream(filePath) overwrites the original contents of the file //FileOutputStream = new FileOutputStream (filePath, true) appended to the back of the file content each time fileOutputStream = new FileOutputStream(filePath , true) ; String str = "hello world" ; fileOutputStream.write(str.getBytes()); //Read str's [0,3] range bytes fileOutputStream.write(str.getBytes() , 0 , 3); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
File Copy
public class z3_File Copy { public static void main(String[] args) throws IOException { String srcFilePath = "D:\\zaizai.jpg" ; String destFilePath = "D:\\zhouzhou.jpg" ; FileInputStream fileInputStream = null ; FileOutputStream fileOutputStream = null ; try { fileInputStream = new FileInputStream(srcFilePath) ; fileOutputStream = new FileOutputStream(destFilePath) ; byte[] bytes = new byte[1024] ; int readLen ; while( (readLen = fileInputStream.read(bytes)) != -1 ){ fileOutputStream.write(bytes , 0 , readLen); } } catch (Exception e) { e.printStackTrace(); }finally { if( fileInputStream != null ){ fileInputStream.close(); } if( fileOutputStream != null ){ fileOutputStream.close(); } } } }
FileReader and FileWriter classes
FileReader and FileWriter are character streams that operate on io by character
FileReader related methods
- new FileReader(File/String)
- read reads a single character each time, returning it if -1 is returned at the end of the file
- read(char []) Bulk reads multiple characters into an array, returning the number of characters read, if -1 is returned at the end of the file
Related API s
- new String(char[]) converts char[] to String
- New String (char[], off, len) converts the specified part of char[] to a String
public class z1_FileReader { /** * fileReader.read() * Read one character at a time * */ @Test public void FileRead(){ String filePath = "D:\\stroe.txt" ; FileReader fileReader = null ; try { fileReader = new FileReader(filePath); int data ; while( (data = fileReader.read()) != -1 ){ System.out.print((char)data); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if( fileReader != null ){ try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void fileReadMore(){ String filePath = "D:\\stroe.txt" ; FileReader fileReader = null ; try { fileReader = new FileReader(filePath) ; int readLen ; char[] chars = new char[1024] ; while( (readLen = fileReader.read(chars)) != -1 ){ String s = new String(chars, 0, readLen); System.out.print(s); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if( fileReader != null ){ try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
FileWriter related methods
- new FileWriter(File/String) override mode, equivalent to the pointer of the stream at the top
- new FileWriter(File/String, true) append mode, equivalent to the pointer to the stream at the end
- write(int) Writes a single character
- write(char[]) to the specified array
- Write (char[], off, len) to the specified part of the specified array
- write(String) Writes the entire string
- Write (String, off, len) Writes the specified part of the string
Related API s
-
String class:
- toCharArray: Convert String to char[]
Note: FileWriter must be closed or flush after use, otherwise the specified file cannot be written!
Node Flow and Processing Flow
Basic Introduction
- Node streams can read and write data from a specific data source, such as FileReader, FileWriter
- Processing streams (also known as wrapper streams) are "connected" to existing streams (node streams or processing streams) to provide programs with more powerful read and write capabilities, such as BufferedReader, BufferedWriter
Differences and connections between node flow and processing flow
- Node streams are bottom/bottom streams that connect directly to data sources
- Processing streams (wrapper streams) wraps node streams, which can either eliminate implementation differences between different node streams or provide a more convenient way to complete input and output.
- Processing streams (also called wrapping streams) wrap node streams using a decorator design pattern that does not directly connect to data sources
The main functions of handling streams are
- Performance improvements: Enhance input and output efficiency mainly by increasing buffers
- Convenient operation: Processing streams provide a series of convenient methods to input and output large quantities of data at a time, making it more flexible and convenient to use
BufferedReader and BufferedWriter - Character Processing Stream
- BufferedReader and BufferedWriter are character streams and read files by character
- When closing a processing stream, you only need to close the outer stream.
Use of BufferedReader
public class z1_BufferdReader { public static void main(String[] args) throws IOException { String filePath = "D:\\stroe.txt" ; BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath)); String line ; while( (line = bufferedReader.readLine()) != null ){ System.out.println(line); } bufferedReader.close(); } }
BufferedWriter
public class z2_BufferedWriter { public static void main(String[] args) throws IOException { String filePath = "D:\\bufferedWriter.txt" ; BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath , true)); bufferedWriter.write("hello1 , world !"); bufferedWriter.newLine(); //Write a System-compliant line break bufferedWriter.write("hello2 , world !"); bufferedWriter.newLine(); bufferedWriter.write("hello3 , world !"); bufferedWriter.close(); } }
BufferedInputStream and BufferedOutputStream - Byte Processing Stream
-
BufferedInputStream is a byte stream and when BufferedInputStream is created, an internal buffer array is created.
-
BufferedOutputStream is a byte stream that implements a buffered output stream where multiple bytes can be written to the underlying output stream instead of invoking the underlying system for each byte write
ObjectInputStream and ObjectOutputStream - Object Flow
Look at a need
Save the int num = 100 int data to a file, note that it is not 100, but int 100, and can recover int 100 directly from the file
Save the Dog dog = new Dog (Little Yellow, 3) object to a file and recover it from the file
The above requirements are the ability to serialize and deserialize basic data types or objects
serialization and deserialization
-
Serialization is when you save data, saving its values and data types
-
Deserialization is about restoring the values and data types of the data when it is restored
-
To enable an object to support serialization, its classes must be serializable, and in order for a class to be serializable, it must implement one of two interfaces
- Serializable//This is a markup interface
- Externalizable
Use of ObjectOutputStream
public class z3_ObjectOutputStream { public static void main(String[] args) throws IOException { String filePath = "D:\\objectOutputStream.dat" ; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath)) ; oos.writeInt(100); oos.writeBoolean(true); oos.writeUTF("week"); oos.writeObject( new Dog("Bangbang" , 3) ); System.out.println("Storage Complete"); oos.close(); } } class Dog implements Serializable { private String name ; private int age ; public Dog(String name, int age) { this.name = name; this.age = age; } }
Matters needing attention
- Read and write in the same order
- Require serialization or deserialization of objects, need to implement Serializable
- SerialVersionUID is simply added to serialized classes to improve version compatibility
- When serializing an object, all of its properties are serialized by default, except for members modified by static or transient s
- When serializing an object, the type of attribute inside is also required to implement the serialization interface
- Serialization is inheritable, that is, if a class has been serialized, all its subclasses have also been serialized by default
InputStreamReader and OutputStreamWriter - Conversion Stream
- A subclass of InputStreamReaderReader that wraps InputStream (byte stream) as a Reader (character stream)
- A subclass of OutputStreamWriterWriter that wraps OutputStream (byte stream) as a Writer (character stream)
- When working with plain text data, it is recommended that byte streams be converted to character streams if they are more efficient and can effectively solve Chinese problems.
- Encoding formats can be specified when using (such as utf-8, gbk, gb2312, ISO8859-1, etc.)
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-1AWsWyXS-1638116605260).) https://pumpkn.xyz/upload/2021/09/image-0608f8cec2c848dca8593d4c95b954b5.png )]
Properties class
-
Collection classes dedicated to reading and writing configuration files
- Configuration file format: key = value
-
Note: Key-value pairs do not need spaces, and values do not need to be quoted together. The default type is String
common method
- load Load Configuration File Key Value Pairs to Properties Object
- list Displays data to the specified device
- getProperty(key) Gets a value based on the key
- SetProperty (key, value) Sets the key-value pair to the Properties object
- store stores key-value pairs in Properties to the configuration file, in idea, saves information to the configuration file, and if it contains Chinese, stores it as unicode code code
public class z1 { public static void main(String[] args) throws IOException { Properties properties = new Properties(); //Load properties file properties.load(new FileReader("src\\mysql.properties")); //Get K-V String user = properties.getProperty("user"); String pwd = properties.getProperty("pwd"); System.out.println(user + " " + pwd); //Modify K-V to add if K does not exist properties.setProperty("user" , "xiaomi") ; properties.setProperty("max" , "200") ; System.out.println(properties.getProperty("user") + " " + properties.getProperty("max")); //Store k-v in file properties.store( new FileOutputStream("src\\mysql.properties") , null); } }