Chapter 13 IO flow
File The use of the class
File Class
File An object of class , Represents a file or a file directory ( Be commonly called : Folder )
File Class declaration in java.io It's a bag
File Class involves the creation of files or file directories 、 Delete 、 rename 、 Modification time 、 File size, etc , It does not involve writing or reading the contents of the file . If you need to read or write the contents of the file , You have to use IO Flow to complete .
follow-up File The object of the class is often passed as an argument to the constructor of the stream , To indicate read or write to " End ".
File Instantiation
File(String filePath)
File(String parentPath,String childPath)
File(File parentFile,String childPath)
The classification of paths
Relative paths : Compared with a certain path , The path indicated .
Absolute path : The path to the file or file directory that contains the drive letter
explain :
IDEA in :
If you develop and use JUnit Unit test method test in , The relative path is the current Module Next .
If you use main() test , The relative path is the current Project Next .
Eclipse in :
Whether using unit testing methods or using main() test , Relative paths are all current Project Next .
Path separator
windows and DOS System default use “\” To express
// D:\ Chen 2\ Baozixue series \Java01_ Baozi studies Java Basics
UNIX and URL Use “/” To express
// home/cyb
File Common methods of class
File Class
public String getAbsolutePath(): Get absolute path
public String getPath() : Get path
public String getName() : Get the name
public String getParent(): Get the upper file directory path . If there is no , return null
public long length() : Get file length ( namely : Number of bytes ). Cannot get the length of the directory .
public long lastModified() : Get the last modification time , Millisecond value
public String[] list() : Get the name array of all files or file directories in the specified directory
public File[] listFiles() : Get all the files in the specified directory or file directory File Array
File Class renaming function
public boolean renameTo(File dest): Rename the file to the specified file path
File Class
public boolean isDirectory(): Determine whether it is a file directory
public boolean isFile() : Determine if it's a document
public boolean exists() : Judge whether it exists
public boolean canRead() : Judge whether it is readable
public boolean canWrite() : Judge whether it is writable
public boolean isHidden() : Determine whether to hide
File Class creation
public boolean createNewFile() : create a file . If the file exists , Do not create , return false
public boolean mkdir() : Create file directory . If this file directory exists , We won't create . If the upper directory of this file directory does not exist , It doesn't create .
public boolean mkdirs() : Create file directory . If the upper file directory does not exist , Create... Together
matters needing attention : If you create a file or the file directory does not have a drive letter path , that , Default in project Under the path .
File Class delete function
public boolean delete(): Delete files or folders
Delete notes :
Java Delete in does not go to the recycle bin . To delete a file directory , Please note that the file directory cannot contain files or file directories
practice
File dir1 = new File("D:/IOTest/dir1");
if (!dir1.exists()) { // If D:/IOTest/dir1 non-existent , Just create it as a directory
dir1.mkdir();
}
// Create to dir1 Is the parent directory , be known as "dir2" Of File object
File dir2 = new File(dir1, "dir2");
if (!dir2.exists()) { // If it doesn't exist yet , Just create it as a directory
dir2.mkdirs();
}
File dir4 = new File(dir1, "dir3/dir4");
if (!dir4.exists()) {
dir4.mkdirs();
}
// Create to dir2 Is the parent directory , be known as "test.txt" Of File object
File file = new File(dir2, "test.txt");
if (!file.exists()) { // If it doesn't exist yet , Just create it as a file
file.createNewFile();
}
//2. Determine whether there is a suffix named .jpg The file of , If there is , Just output the file name
@Test
public void test1(){
File srcFile = new File("d:\\code");
String[] fileNames = srcFile.list();
for(String fileName : fileNames){
if(fileName.endsWith(".jpg")){
System.out.println(fileName);
}
}
}
public void test2(){
File srcFile = new File("d:\\code");
File[] listFiles = srcFile.listFiles();
for(File file : listFiles){
if(file.getName().endsWith(".jpg")){
System.out.println(file.getAbsolutePath());
}
}
}
//3. Traverse the specified directory all file names , Include files in the subdirectory .
// expand 1: And calculate the space occupied by the specified directory
// expand 2: Delete the specified file directory and all the files under it
public static void printSubFile(File dir) {
// Print sub files of directory
File[] subfiles = dir.listFiles();
for (File f : subfiles) {
if (f.isDirectory()) {// File directory
printSubFile(f);
} else {// file
System.out.println(f.getAbsolutePath());
}
}
}
// List file Subordinate to the directory , If it's subordinate to the directory , Then list the subordinates of your subordinates , By analogy
// It is recommended to use File Class File[] listFiles()
public void listAllSubFiles(File file) {
if (file.isFile()) {
System.out.println(file);
} else {
File[] all = file.listFiles();
// If all[i] It's a document , Print directly
// If all[i] Is a directory , And then get the next level of it
for (File f : all) {
listAllSubFiles(f);// Recursively call : Call yourself recursion
}
}
}
// expand 1: Find the space size of the specified directory
// Find the total size of a directory
public long getDirectorySize(File file) {
// file It's a document , Then go straight back file.length()
// file Is a directory , Add up all the sizes of its next level to get its total size
long size = 0;
if (file.isFile()) {
size += file.length();
} else {
File[] all = file.listFiles();// obtain file Next level
// Add up all[i] Size
for (File f : all) {
size += getDirectorySize(f);// f Size ;
}
}
return size;
}
// expand 2: Delete the specified directory
public void deleteDirectory(File file) {
// If file It's a document , direct delete
// If file Is a directory , Take out the next level first , Then delete yourself
if (file.isDirectory()) {
File[] all = file.listFiles();
// The circular deletion is file Next level
for (File f : all) {// f representative file Every subordinate of
deleteDirectory(f);
}
}
// Delete yourself
file.delete();
}
IO Flow overview
Input input: Read external data ( disk 、 Data from storage devices such as optical disks ) To Program ( Memory ) in .
Output output: Put the program ( Memory ) Data output to disk 、 CD and other storage devices Prepare for .
The dividing line is memory : In memory processing is Input stream 、 Out of memory is the output stream
The most basic flow
( Abstract base class ) | Byte stream | Character stream |
---|---|---|
Input stream | InputStream | Reader |
Output stream | OutputStream | Writer |
Classification of flows
- Operating data units : Byte stream 、 Character stream
- The flow of data : Input stream 、 Output stream
- The role of flow : Node flow 、 Processing flow
Flow architecture
explain : The red box corresponds to IO Streaming 4 Abstract base classes .
The flow in the blue box needs our attention .
- The basic four abstract base classes
- Four of the documents
- Four buffers
- Two streams of transformation
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutStreamWriter(System.out));
Several stream structures are highlighted
Input 、 The standardization process of output
Input process
① establish File Class object , Indicates the source of the data read .( This file must exist )
② Create the corresponding input stream , take File Class as parameters , In the constructor of the incoming stream
③ The specific reading process :
Create the corresponding byte[] or char[].
④ Close stream resource
explain : The exception in the program needs to use try-catch-finally Handle .
InputStream & Reader
InputStream and Reader Is the base class for all input streams
InputStream
int read()
int read(byte[] b)
int read(byte[] b, int off, int len)
Reader
int read()
int read(char [] c)
int read(char [] c, int off, int len)
// Files opened in the program IO Resources do not belong to resources in memory , The garbage collection mechanism can't recover the money
Source , So you should explicitly close the file IO resources
// FileInputStream Get input bytes from a file in the file system .FileInputStream
Used to read raw byte streams such as non text data . To read a character stream , Need to use FileReader
Output process
① establish File Class object , Indicate the location of the written data .( Don't ask this file to exist )
② Create the corresponding output stream , take File Class as parameters , In the constructor of the incoming stream
③ The specific writing process :
write(char[]/byte[] buffer,0,len)
④ Close stream resource
explain : The exception in the program needs to use try-catch-finally Handle .
OutputStream & Writer
void write(int b/int c);
void write(byte[] b/char[] cbuf);
void write(byte[] b/char[] buff, int off, int len);
void flush();
void close(); You need to refresh , Close the stream again
// Because character streams operate directly on characters , therefore Writer You can replace character arrays with strings ,
That is to String Object as parameter
void write(String str);
void write(String str, int off, int len);
// FileOutputStream Get the output bytes from a file in the file system .FileOutputStream
Used to write raw byte streams such as non text data . To write a character stream , Need to use FileWriter
Node flow ( Stream or file )
FileReader Use
1. Create a stream object , Load an existing file into the stream .
FileReader fr = new FileReader(new File(“Test.txt”));
2. Create an array of temporary data storage .
char[] ch = new char[1024];
3. Call the read method of the stream object to read the data in the stream into the array .
fr.read(ch);
4. close resource .
fr.close();
@Test
public void testFileReader1() {
FileReader fr = null;
try {
//1.File Class instantiation
File file = new File("hello.txt");
//2.FileReader Instantiation of a stream
fr = new FileReader(file);
//3. Read in operation
//read(char[] cbuf): Return every read in cbuf The number of characters in the array . If the end of the file is reached , return -1
char[] cbuf = new char[5];
int len;
while((len = fr.read(cbuf)) != -1){
// Mode one :
// The wrong way to write
// for(int i = 0;i < cbuf.length;i++){
// System.out.print(cbuf[i]);
// }
// Correct writing
// for(int i = 0;i < len;i++){
// System.out.print(cbuf[i]);
// }
// Mode two :
// The wrong way to write , It's the wrong way to write it
// String str = new String(cbuf);
// System.out.print(str);
// Correct writing
String str = new String(cbuf,0,len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fr != null){
//4. Closure of resources
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
explain :
- read() The understanding of the : Returns a character read in . If the end of the file is reached , return -1
- Exception handling : In order to ensure that the stream resource can be closed . Need to use try-catch-finally Handle
- The file read in must exist , Otherwise it will be reported FileNotFoundException
FileWriter Use
1. Create a flow object , Create data storage files
FileWriter fw = new FileWriter(new File(“Test.txt”));
2. Call the write method of the stream object , Write data to the stream
fw.write(“atguigu-songhongkang”);
3. Close stream resource , And empty the data in the stream to the file .
fw.close();
@Test
public void testFileWriter() {
FileWriter fw = null;
try {
//1. Provide File Class object , Indicate the document written to
File file = new File("hello1.txt");
//2. Provide FileWriter The object of , For writing data
fw = new FileWriter(file,false);
//3. Written operations
fw.write("I have a dream!\n");
fw.write("you need to have a dream!");
} catch (IOException e) {
e.printStackTrace();
} finally {
//4. The closure of streaming resources
if(fw != null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
explain :
- Output operation , Corresponding File Can not exist . No exception will be reported
- File If the file in the corresponding hard disk does not exist , In the process of output , This file will be created automatically .
- File If the file in the corresponding hard disk exists :
- If the constructor used by the stream is :FileWriter(file,false) / FileWriter(file): An overlay of the original file
- If the constructor used by the stream is :FileWriter(file,true): The original file will not be overwritten , It's an addition to the original document
Copy of text files
@Test
public void testFileReaderFileWriter() {
FileReader fr = null; // Using a character stream
FileWriter fw = null;
try {
//1. establish File Class object , Indicate the documents read in and written out
File srcFile = new File("hello.txt");
File destFile = new File("hello2.txt");
// Can't use character stream to process byte data such as pictures
// File srcFile = new File(" Love and friendship .jpg");
// File destFile = new File(" Love and friendship 1.jpg");
//2. Create objects for input and output streams
fr = new FileReader(srcFile);
fw = new FileWriter(destFile);
//3. Data reading and writing operations
char[] cbuf = new char[5];
int len;// Record every time you read in cbuf The number of characters in the array
while((len = fr.read(cbuf)) != -1){
// Every time you write len Characters
fw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4. Close stream resource
// Mode one :
// try {
// if(fw != null)
// fw.close();
// } catch (IOException e) {
// e.printStackTrace();
// }finally{
// try {
// if(fr != null)
// fr.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// Mode two :
try {
if(fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileInputStream / FileOutputStream Use
For text files (.txt,.java,.c,.cpp), Using character stream processing
For non text files (.jpg,.mp3,.mp4,.avi,.doc,.ppt,...), Using byte stream processing
// Picture reproduction
@Test
public void testFileInputOutputStream() {
FileInputStream fis = null; // Byte stream
FileOutputStream fos = null;
try {
//1. Making documents
File srcFile = new File(" Love and friendship .jpg");
File destFile = new File(" Love and friendship 2.jpg");
//2. Flow making
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//3. The process of copying
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer)) != -1){
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
//4. Closed flow
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The relative path is IDEA and Eclipse The difference used in ?
IDEA:
- If you use the unit testing method , The relative path is based on the current Module Of .
- If you use main() test , The relative path is based on the current Project Of .
Eclipse:
- Unit testing method or main(), Relative paths are based on the current situation Project Of .
Buffer flow
The class involved in the buffer flow
- BufferedInputStream
- BufferedOutputStream
- BufferedReader
- BufferedWriter
The buffer stream needs to be “ Socket joint ” On the corresponding node stream , The buffer stream can be divided into :
effect
effect : Provide stream reading 、 The speed of writing
The reason to improve the speed of reading and writing : Internally, a buffer is provided . By default 8kb
Use BufferedInputStream and BufferedOutputStream: Processing non text files
// How to copy files
public void copyFileWithBuffered(String srcPath,String destPath){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1. Making documents
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//2. Flow making
//2.1 Making node flow
FileInputStream fis = new FileInputStream((srcFile));
FileOutputStream fos = new FileOutputStream(destFile);
//2.2 Create a buffer stream
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3. The details of copying : Read 、 write in
byte[] buffer = new byte[1024];
int len;
while((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4. Resources to shut down
// requirement : Turn off the outer stream first , Then close the inner stream
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// explain : While closing the outer laminar flow , The inner layer flow will be automatically closed . About the closure of the inner laminar flow , We can omit .
// fos.close();
// fis.close();
}
}
Use BufferedReader and BufferedWriter: Processing text files
@Test
public void testBufferedReaderBufferedWriter(){
BufferedReader br = null;
BufferedWriter bw = null;
try {
// Create files and corresponding streams
br = new BufferedReader(new FileReader(new File("dbcp.txt")));
bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));
// Read and write operations
// Mode one : Use char[] Array
// char[] cbuf = new char[1024];
// int len;
// while((len = br.read(cbuf)) != -1){
// bw.write(cbuf,0,len);
// // bw.flush();
// }
// Mode two : Use String
String data;
while((data = br.readLine()) != null){
// Method 1 :
// bw.write(data + "\n");//data Line breaks are not included in
// Method 2 :
bw.write(data);//data Line breaks are not included in
bw.newLine();// Provide line feed operations
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// close resource
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Converted flow
The class involved in the conversion flow : Belongs to the character stream
InputStreamReader: Will a byte The input stream of is converted to character The input stream of
decode : byte 、 Byte array ---> A character array 、 character string
OutputStreamWriter: Will a character The output stream of the byte The output stream of
code : A character array 、 character string ---> byte 、 Byte array
To put it bluntly . Look at the picture below , Is to use character streams to process byte streams
Provides conversion between byte stream and character stream
Typical implementation
@Test
public void test1() throws IOException {
FileInputStream fis = new FileInputStream("dbcp.txt");
// InputStreamReader isr = new InputStreamReader(fis);// Use the default character set of the system
// Parameters 2 Indicates the character set , Which character set to use , Depends on the file dbcp.txt The character set used when saving
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");// Use the default character set of the system
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
String str = new String(cbuf,0,len);
System.out.print(str);
}
isr.close();
}
@Test
public void test2() throws Exception {
//1. Making documents 、 Flow making
File file1 = new File("dbcp.txt");
File file2 = new File("dbcp_gbk.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
InputStreamReader isr = new InputStreamReader(fis,"utf-8");
OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
//2. Reading and writing process
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
osw.write(cbuf,0,len);
}
//3. close resource
isr.close();
osw.close();
}
// The way the document is encoded ( such as :GBK), Determines the character set to use when parsing ( It can only be GBK).
Common coding table
ASCII: American standard information interchange code .
Use a byte of 7 Bits can represent .
ISO8859-1: Latin code table . European Code watch
Use a byte of 8 Who said .
GB2312: Chinese code table of China . Up to two bytes encode all characters
GBK: China's Chinese coding table upgrade , It integrates more Chinese characters and symbols . Up to two byte encoding
Unicode: International Standard Code , It integrates all the characters currently used by humans . Assign a unique character code to each character . All the text is represented in two bytes .
UTF-8: Variable length encoding , You can use 1-4 Bytes to represent a character .
The use of other streams
Standard input and output streams
System.in: Standard input stream , Input from the keyboard by default
System.out: Standard output stream , Output from the console by default
Modify the default input and output behavior
System Class setIn(InputStream is) / setOut(PrintStream ps) Method to specify the input and output streams .
Print stream
PrintStream and PrintWriter
Provides a series of overloaded print() and println() Method , Output for multiple data types
System.out The return is PrintStream Example
Data flow
DataInputStream and DataOutputStream
effect
A variable or string used to read or write basic data types
Example
-
Put the string in memory 、 The variables of the basic data type are written out to the file .
@Test public void test3() throws IOException { //1. DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt")); //2. dos.writeUTF(" Liu Jianchen "); dos.flush();// Refresh operation , Write data in memory to a file dos.writeInt(23); dos.flush(); dos.writeBoolean(true); dos.flush(); //3. dos.close(); }
-
Read the basic data type variables and strings stored in the file into memory , Save in variable .
@Test public void test4() throws IOException { //1. DataInputStream dis = new DataInputStream(new FileInputStream("data.txt")); //2. String name = dis.readUTF(); int age = dis.readInt(); boolean isMale = dis.readBoolean(); System.out.println("name = " + name); System.out.println("age = " + age); System.out.println("isMale = " + isMale); //3. dis.close(); }
The use of object streams
Object flow
ObjectInputStream and ObjectOutputStream
effect
ObjectOutputStream: Objects in memory ---> Files in storage 、 It's transmitted over the Internet : Serialization process
ObjectInputStream: Files in storage 、 Received over the Internet ---> Objects in memory : Deserialization process
The object serialization mechanism allows the Java Object to platform independent binary stream , This allows the binary stream to be persistent on disk , Or transfer this binary stream over the network to another network node .// When other programs get this binary stream , It can be restored to the original Java object
Serialization and deserialization
serialize
@Test
public void testObjectOutputStream(){
ObjectOutputStream oos = null;
try {
//1.
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
//2.
oos.writeObject(new String(" I love tian 'anmen square in Beijing "));
oos.flush();// Refresh operation
oos.writeObject(new Person(" Wang Ming ",23));
oos.flush();
oos.writeObject(new Person(" Zhang xueliang ",23,1001,new Account(5000)));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos != null){
//3.
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Deserialization
@Test
public void testObjectInputStream(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
String str = (String) obj;
Person p = (Person) ois.readObject();
Person p1 = (Person) ois.readObject();
System.out.println(str);
System.out.println(p);
System.out.println(p1);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(“data.txt"));
Person p = new Person(" Han Meimei ", 18, " Zhonghua Street ", new Pet());
oos.writeObject(p);
oos.flush();
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(“data.txt"));
Person p1 = (Person)ois.readObject();
System.out.println(p1.toString());
ois.close();
The class of the object that implements serialization needs to satisfy
- Need to implement interface :Serializable
- The current class provides a global constant :serialVersionUID
- Except for the present Person Class needs to be implemented Serializable Beyond the interface , It is also necessary to ensure that its internal properties are serializable .( By default , Basic data types are serializable )
Add :ObjectOutputStream and ObjectInputStream Cannot serialize static and transient Modified member variables
Path、 Paths、Files The use of the class
NIO Instructions for use
- Java NIO (New IO,Non-Blocking IO) It's from Java 1.4 A new set of IO API, Can replace the standard Java
IO AP. - NIO Original IO The same function and purpose , But in a totally different way ,NIO Support for buffer oriented (IO It's stream oriented )、 Channel based IO operation .
- NIO It will read and write files in a more efficient way .
- With JDK 7 Release ,Java Yes NIO It's a huge expansion , Enhanced support for file processing and file system features , So we call them NIO.2.
Path Use ---jdk7 Provide
import java.io.File;
File file = new File("index.html");
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("index.html");
Path It can be seen as File Upgrade version of class , Actually quoted information The source may not exist