当前位置:网站首页>Chapter VIII IO
Chapter VIII IO
2022-07-20 18:58:00 【¥ running snail】
File class
● File Class is java.io A very important class in the package ;
● File Class can represent a file , It can also represent a directory , In a program File Class object can substitute Table a file or directory ;
● File Object can operate on the properties of a file or directory , Such as : file name 、 Last modified date 、 file Size, etc ;
● File Object cannot manipulate the specific data of the file , That is, you can't read the file directly / Write operations .
File Construction method of class
Fang Law primary type :File(String pathname)
say bright : Specified file ( Or directory ) Create file object with name and path
// Create a file in the current directory with aaa.txt The file object associated with the file name
File f1 = new File("aaa.txt");
// Indicate the detailed path and file name , Please note the double slash or backslash
File f2 = new File("D:\\Java\\Hello.java");
// Indicate the detailed path and directory name , Notice the double slash
File f3 = new File("D:\\Java");
● File Common methods of class
1、isDirectory(): Judge this File The path represented by the object indicates whether it is a folder , Only File Object represents that the path exists and is a directory true, Otherwise return to false.
2、isFile(): Judge this File Whether the path represented by the object is a standard file , Only File Only when the representative path exists and is a standard file true, Otherwise return to false.
3、getPath(): return File The string path represented by the object .
4、getName(): Returns the last level folder name of the file or directory represented by this object .
5、getParent(): Back here File Object's parent directory pathname ; If no parent directory is specified for this pathname , Then return to null.
6、getParentFile(): return File The parent directory of the object File example ; If File Object has no parent directory , Then return to null.
import java.io.File;
public class Work {
public static void main(String[] args){
File file = new File("E:\\ Netease has a dictionary \\Youdao\\Dict\\guid.dat");
if(file.isDirectory()) //1、 Determine whether the path is a folder .
{
System.out.println("YES");
}else{
System.out.println("NO");
}
if(file.isFile()) //2、 Determine whether the path is a file .
{
System.out.println("yes");
}else{
System.out.println("no");
}
System.out.println(file.getPath()); //3、 Path name .
System.out.println(file.getName()); //4、 The last layer name .
System.out.println(file.getParent()); //5、 Remove the path name of the last layer .
File file1 = file.getParentFile(); //6、 return File example , The path is the path that removes the last layer .
System.out.println(file1.getPath());
}
}
7、 renameTo(): Rename this File File represented by object , Renaming is successful. Return true, Otherwise return to false.
8、 mkdir(): Create this File Directory specified by class object ( Folder ), Does not contain parent directory . Create successfully back true, Otherwise return to false.
9、 mkdirs(): Create this File The directory specified by the object , Include all required but nonexistent parent directories , Create successfully return true; Otherwise return to false. Be careful , When this operation fails, some necessary parent directories may have been successfully created .
10、createNewFile(): If the specified file does not exist and is successfully created , Then return to true; If the specified file already exists , Then return to false; If the directory of the created file does not exist, the creation fails and IOException abnormal .
11、exists(): Determine if a file or directory exists .
import java.io.File;
import java.io.IOException;
public class Work {
public static void main(String[] args) throws IOException{
File file = new File("D:\\Tom\\Jim.txt");
System.out.println(file.renameTo(new File("D:\\Tom\\Jom.txt"))); //7、 Change of name , Must be... In parentheses File example .
Boolean flag = new File("D:\\Tom\\Lacy").mkdir(); //8、 Create a layer of folders .
System.out.println(flag);
flag = new File("D:\\Tom\\a\\b").mkdirs(); //9、 You can create multi-level folders .
System.out.println(flag);
flag = new File("D:\\Tom\\a.doxc").createNewFile(); //10、 Create a layer of files .
System.out.println(flag);
System.out.println(new File("D:\\Tom\\a.doxc").exists()); //11、 Judge whether the file or folder exists .
}
}
12、 delete(): Delete File Directory or file represented by class object . If the object represents a directory , The directory must be empty to delete ; If the file or directory is deleted successfully, return true, otherwise false.
13、 list(): Return from File Object corresponds to a string array of file names or folder names contained in the directory .
14、 listFiles(): Return by current File Object is composed of the file path or folder path contained in the corresponding directory File An array of types .
15、 separator: Use slashes or backslashes when specifying file or directory paths , But considering cross platform , Slashes and backslashes are best used File Class separator Attribute to represent .
import java.io.File;
import java.io.IOException;
public class Work {
public static void main(String[] args) throws IOException{
File file = new File("D:\\Tom\\Jom.txt");
File file1 = new File("D:"+File.separator+"Tom"); //15、File.separator It will be automatically generated according to the operating system \\ perhaps /.
System.out.println(file.delete()); //12、 Delete files or folders with empty contents .
String[] names = file1.list(); //13、 Return the file name and folder name under this folder .
for (String name : names) {
System.out.println(name);
}
File[] files = file1.listFiles(); //14、 Return the files and folders under this folder File Instance array .
for (File file2 : files) {
System.out.println(file2.getPath());// The output path .
}
}
}
boolean exists()
Judge whether the file exists , There is returned true, Otherwise return to false
boolean isFile()
Determine if it is a file , It's a file return true, Otherwise return to false
boolean isDirectory()
Determine whether it is a directory , Is the directory return true, Otherwise return to false
String getName()
Get the name of the file
long length()
Get the length of the file ( Number of bytes )
boolean createNewFile()
throws IOException
Create a new file , Create successfully return true, Otherwise return to false, It is possible to throw
IOException abnormal , Must capture
boolean delete()
Delete file , Delete successful return true, Otherwise return to false
public String[] list()
Name the subdirectories and files under the directory , Back to String Array
public File[] listFiles()
Return the subdirectories and file instances under the directory to File Array
The concept of input and output
● Input and output (I/O)
Read the data on the computer hard disk into the program , It's called input , namely input, data-driven read operation
Write data from a program to an external device , It's called output , namely output, data-driven write
operation
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-6NyMlu1k-1626494909062)(C:\Users\ He Wenqiang \AppData\Roaming\Typora\typora-user-images\1624964940833.png)]
Byte stream and character stream
● Common classes in byte stream
Byte input stream FileInputStream
Byte output stream FileOutputStream
1、FileInputStream( File byte input stream )
package io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ByteInput {
public static void main(String[] args) throws IOException {
//1、 Define the file to use
File file = new File("F:" + File.separator + "byteInput.txt");
file.createNewFile(); // When the file exists, it will not be executed , It will be executed when it does not exist
//2、 Define byte input stream as file input stream
InputStream input = new FileInputStream(file);
byte[] b = new byte[(int) file.length()]; // file.length() Get the length of the file and return long type
int len = input.read(b);
input.close();
//3、 Verify input results
System.out.println(" The content length of the file is : " + len);
System.out.println(" The contents of the file are : " + new String(b));
}
}
2.FileOutputStream( File byte output stream ) Realize byte by byte processing of file content
package io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class ByteOutput {
public static void main(String[] args) throws IOException{
//1、 Get the file to operate
File file=new File("F:"+File.separator+"byteOutput.txt");
file.createNewFile();
//2、 Write the specified content
String str="I Like Java!";
OutputStream output=new FileOutputStream(file);
output.write(str.getBytes(), 0, str.length()); // Write string
output.close();
}
}
● Common classes in character stream
Character input stream FileReader
Character output stream FileWriter
3、FileReader( File character input stream ) Realize the character by character processing of file content
package io;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class CharInput {
public static void main(String[] args) throws IOException {
//1、 Specify the file to operate on
File file=new File("F:"+File.separator+"charInput.txt");
file.createNewFile();
//2、 Specify byte input stream
Reader reader=new FileReader(file);
char[] c=new char[(int)file.length()];
int len=reader.read(c);
reader.close();
//3、 verification
System.out.println(" The length of the character stream read file is : "+len);
System.out.println(" The character stream reads the contents of the file : "+new String(c));
}
}
4、FileWriter( File character output stream ) Realize the character by character processing of file content
package io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class CharOutput {
public static void main(String[] args) throws IOException {
File file = new File("F:" + File.separator + "charOutput.txt");
file.createNewFile();
Writer writer = new FileWriter(file);
writer.write("I Love Basketball!", 0, 18);
writer.close();
}
}
Input stream and output stream
● Streams are divided into... According to the transmission direction of data :
Input stream : Read the input stream into the program .
Output stream : Writing out of a program is called an output stream .
● InputStream and OutputStream Subclasses of are byte streams
Can read and write binary files , Mainly deal with audio 、 picture 、 song 、 Byte stream , processing unit by 1 Bytes .
● Reader and Writer Subclasses of are character streams
It mainly deals with characters or strings , The character stream processing unit is 1 Characters .
Byte data to be read by byte stream , To get the corresponding text from the specified encoding table .
I / O byte stream
● InputStream Basic approach
Read a byte and return as an integer (0~255), If you return -1 Has reached the end of the input stream .
int read() throws IOException
Read a series of bytes and store them in an array buffer,
Returns the number of bytes actually read , If you have reached the end of the input stream before reading, return -1
int read(byte[] buffer) throws IOException
Close the stream to free up memory resources
void close() throws IOException
● OutputStream Basic approach
Write a byte of data to the output stream , The byte data is a parameter b It's low 8 position
void write(int b) throws IOException
From the specified position in an array of byte types (off) At the beginning
len Bytes written to the output stream
void write(byte[] b, int off, int len) throws IOException
Close the stream to free up memory resources
void close() throws IOException
Node flow and processing flow
● According to different packaging types, the flow is divided into
Node flow
Processing flow
● Node flow :
If the stream encapsulates a specific data source , Such as file 、 character string 、 String array, etc ,
It is called node flow .
● Processing flow .
If the stream encapsulates other stream objects , It is called processing flow .
The processing stream provides buffering , Improve reading and writing efficiency , At the same time, some new methods have been added .
● Common classes in node flow
Byte input stream FileInputStream
Byte output stream FileOutputStream
Character input stream FileReader
Character output stream FileWriter
● Common classes in processing streams
Buffered byte output stream BufferedOutputStream
Buffer byte input stream BufferedInputStream
Buffer character input stream BufferedReader
Buffer character output stream BufferedWriter
// Character input stream
BufferedReader(Reader in)// Create a 32 Byte buffer
BufferedReader(Reader in, int size)//size To customize the size of the cache
// Character output stream
BufferedWriter(Writer out)
BufferedWriter(Writer out, int size)
// Byte input stream
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)
// Byte output stream
BufferedOutputStream(OutputStream in)
BufferedOutputStream(OutputStream in, int size)
I / O character stream
• Reader Basic approach
Read a character and return it as an integer ,
If you return -1 Has reached the end of the input stream .
int read() throws IOException
Read a series of characters and store them in an array buffer,
Returns the actual number of characters read , If you have reached the end of the input stream before reading, return -1
int read( char[] cbuf) throws IOException
close
void close() throws IOException
• Writer Basic approach
Write a character data to the output stream , The byte data is a parameter b Of 16 position
void write(int c) throws IOException
The data in an array of character types is written to the output stream ,
void write( char[] cbuf) throws IOException
From the specified position in an array of character types (off set) At the beginning
length Write characters to the output stream
void write( char[] cbuf, int off set, int length) throws IOException
close
void close() throws IOException
package com.zch.io;
import java.io.File;
import java.util.Date;
/**
stay src Created in the root directory FileInfo class , Create a file object in the main method of this class , adopt File class , Get information about the file
@author zch
*/
public class FileInfo {
public static void main(String[] args) {
String filePath ="src/com/zch/io/FileInfo.java";
// Create a file object according to the specified path
File file = new File(filePath);
System.out.println(" File name :" + file.getName());
System.out.println(" Does the file exist :" + file.exists());
System.out.println(“ The relative path of the file :” + file.getPath());
System.out.println(“ The absolute path to the file :” + file.getAbsolutePath());
System.out.println(“ Whether it is an executable file :” + file.canExecute());
System.out.println(“ The file can be read :” + file.canRead());
System.out.println(“ Files can be written to :” + file.canWrite());
System.out.println(“ File parent path :” + file.getParent());
System.out.println(“ file size :” + file.length() + “B”);
System.out.println(“ File last modified :” + new Date(file.lastModified()));
System.out.println(“ Whether the file type :” + file.isFile());
System.out.println(“ Is it a folder :” + file.isDirectory());
}
}
Print flow
Print Print stream : Only output, no input
The print stream is divided into byte print stream and character print stream
PrintWriter: Character print stream
print Method can print various types of data
Object input and output streams
● Object : Its main function is to write and read object information . Object information Once written to the file, the information of the object can be persistent
Object output stream : ObjectOutputStream
Object input stream : ObjectInputStream
● To save the serialized object , You need to output the stream through the object (ObjectOutputStream)
Save object state , Then input the stream through the object (ObjectInputStream) Restore the object state .
stay ObjectInputStream of use readObject() Method can directly read an object , ObjectOutputStream of use writeObject() Method to save the object directly to the output stream .
Object serialization
● The lifetime of an object usually ends with the termination of the program that generated it .
occasionally , You may need to save the state of the object , Restore objects when needed .
● Object to write the specified object to a file , It's the process of serializing objects , object The input stream of will specify the process of reading the serialized file , Is the process of object deserialization . since The output stream of an object writes an object to a file, which is called object serialization , So we must realize Serializable Interface .
Serializable There are no methods in the interface . When a class declares an implementation Serializable After the interface , Indicates that the class can be serialized .
You can generate a number in the class
private static final long serialVersionUID = -5974713180104013488L; Random generation Unique serialVersionUID Used to indicate the compatibility between different versions of serialized classes . A class in The corresponding object has been serialized and modified , The object can still be deserialized correctly
public class Example {
public static void main(String[] args) {
User user = new User("Tom", "111", 21);
try {
FileOutputStream fos = new FileOutputStream("C:\\Example.txt");
// Create an output stream object , Make it possible to write objects to files
ObjectOutputStream oos = new ObjectOutputStream(fos);
// Write object to file
oos.writeObject(user);
System.out.println(" Modify the previous user's information :");
System.out.println(" user name :" + user.name);
System.out.println(" Original password :" + user.password);
System.out.println(" Age :" + user.age);
FileInputStream fis = new FileInputStream("C:\\Example.txt");
// Create an input stream object , Make it possible to read data from files
ObjectInputStream ois = new ObjectInputStream(fis);
user = (User) ois.readObject();
user.setPassword("222");
System.out.println(" Modified user information :");
System.out.println(" user name :" + user.name);
System.out.println(" The changed password :" + user.password);
System.out.println(" Age :" + user.age);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class User implements Serializable {
String name;
String password;
int age;
User(String name, String password, int age) {
this.name = name;
this.password = password;
this.age = age;
}
public void setPassword(String password) {
this.password = password;
}
}
边栏推荐
- What is enterprise firewall and what is strategy?
- MATLAB realizes the wind speed conversion of tropical cyclone in different wind periods
- matlab获取原数组在排序后数组中的位置
- Matlab数组A中删除数组B的元素
- [software testing] what kind of resume can HR like at a glance
- 第十章:线程
- Force deduction solution summary 731- my schedule II
- vscode 保存设置配置参数到用户与工作区的区别
- Installation hors ligne du cobbler
- 剪绳子
猜你喜欢
MATLAB realizes LMDI decomposition method (including zero value processing)
Solution to the problem of garbled code in visual code terminal
Matlab cell保存为.csv格式
Matlab绘制95%置信区间图
odoo基础开发之CURD(增、删、查、改)
Are you still worried about the implementation plan change for Oracle database migration?
You can definitely use the carefully selected 100 soft test high-frequency interview questions before the interview
mysql迁移金仓数据库主键、索引丢失问题解决方案
Go fastdfs distributed file system construction (implementation sorting)
疫情之下,软件测试的出路在哪?
随机推荐
There are 13 steps to install pychart, isn't it? (super detailed tutorial)
VRRP技术(详解)
101 questions in software testing interview (with answers)
CPU reads and writes to memory
Software testing post - can you stand the torture of the three souls during the interview?
php7.4升级php8.0后重启系统网站访问异常问题
教你使用CANN将照片一键转换成卡通风格
华云数据荣获可持续技术创新杰出贡献企业
测试岗成功有没有捷径,我告诉你,唯一的捷径就是不走弯路
MySQL migration gold warehouse database primary key, index loss solution
Under the epidemic, where is the way out for software testing?
JMeter practical operation -- database data drive
软件测试与应用期末复习
Matlab计算质心
MIT6.S081-Lab10 mmap [2021Fall]
性能提升30倍丨基于 DolphinDB 的 mytt 指标库实现
项目经验总结——送给测试岗做项目的朋友们
多线程FTP项目(4)—— Mysql数据库 + FTP
Is there a requirement for the number of rows in ODPs SQL in dataworks? Will an error be reported if it is too long
话实践,行实干,成实事:“巡礼”数字化的中国大地