当前位置:网站首页>IO stream - file - properties
IO stream - file - properties
2022-07-29 06:58:00 【A very lazy person】
This paper mainly introduces java Relevant knowledge of midstream , First introduced IO Classification of flows ( From different angles to IO Stream classification ), Secondly, the byte stream and character stream are introduced in detail ( Divide according to the minimum unit convection of data transmission ) Knowledge , It includes the common byte stream and character stream , Then it introduces the relevant knowledge of the document , Finally, common configuration files are introduced properties Use relevant knowledge in combination with flow !
One 、IO Flow action and classification
1. The concept of flow
- Concept : Pipeline for data transmission
2.IO The role of flow
- effect : Current program and other documents ( Memory , file ) Data transmission pipeline
3.IO Classification of flows
Classification by flow direction
- Input stream : Take data from elsewhere ( Memory 、 Disk files ) Transfer to the program
- Output stream : Output the data in the program to other places ( Memory 、 Disk files )
Classify according to the smallest data unit transmitted
- Byte stream : The smallest unit of data transmitted is byte(
It can transmit any kind of data)- Character stream : The smallest unit of transmission is char( Only text content can be output , Cannot transmit audio , video , Pictures and other data )
By function
- Node flow : Data will not be processed
- Filter flow : Can process data
Two 、 Byte stream
system :
- InputStream: all
Byte input streamParent class of , Is an abstract class- OutputStream: all
Byte output streamParent class of , Is an abstract class
1. File byte stream
- FileInputStream: From file to program
- FileOutputStream: From program to file
eg: Copy of documents
public static void main(String[] args) throws IOException {
// Where to read the file into the program
FileInputStream fis=new FileInputStream("E:\\text01.txt");
// Which file is read from the program ,true Indicates whether to add
FileOutputStream fos=new FileOutputStream("E:\\text02.txt",true);
byte[] bytes=new byte[1024];
int len=0;
// Copy
while((len=fis.read(bytes))!=-1) {
fos.write(bytes, 0, len); // Copy files array by array
fos.flush();
}
// Shut off flow
fis.close();
fos.close();
System.out.println("OVER!");
}
2. Memory byte stream
- ByteArrayInputStream: From memory to program
- ByteArrayOutputStream: From program to memory (
toByteArray(): Get the data in memory connected by the memory stream)Be careful :
- Using memory byte stream can solve the problem of garbled data read by file stream ( If byte data is used to read, the last position read is just half of a Chinese character )
- It is not common to use memory byte streams to manipulate files , Because if the file is too large , Reading it all into memory may cause running memory overflow
eg: Memory stream example
//1. Read data in memory
public static void readMemory() throws IOException {
// String constants are stored in the constant pool of running memory at run time
byte[] bytes=" This is the data in the running memory ".getBytes();
ByteArrayInputStream bis=new ByteArrayInputStream(bytes);
// Read b in
byte[] b=new byte[1024];
int len = bis.read(b);
bis.close();
String str=new String(b, 0, len);
System.out.println(str);
}
//2. Prevent partial garbled code in the file stream
public static void writeMemory() throws IOException {
FileInputStream fis=new FileInputStream("E:\\text01.txt");
// There is no need to give parameters ( Data can be stored directly in memory )
ByteArrayOutputStream bos=new ByteArrayOutputStream();
byte[] b=new byte[1024];
int len=0;
while((len=fis.read(b))!=-1) {
// Store the value in bos Responsible running memory
bos.write(b, 0, len);
bos.flush();
}
// take bos The value of the responsible memory area is read out in the form of an array
byte[] bytes = bos.toByteArray();
bos.close();
fis.close();
System.out.println(new String(bytes));
}
public static void main(String[] args) throws IOException {
readMemory();
writeMemory();
}
3. Buffer byte stream (
Filter flow)
- BufferedInputStream
- BufferedOutputStream
effect : Provide reading and writing efficiency :Reduce the number of data handling , Add buffer in data handling , Temporarily save the data to the buffer , When the data in the buffer accumulates to a certain value, the data in the buffer will be transported to the other end at one timeConstructors :With BufferedInputStream For example
- Mode one : Can provide a
InputStreamObject of type , Its default buffer size is 8k( You can see the source code )- Mode two : Can provide a
InputStreamObject of type and buffer sizesize( The unit is byte )
4. Object byte stream
ObjectInputStream
ObjectOutputStreameffect :
- Store objects in a file , Or read the object stored in the file into the program
Be careful :
Class implementation Serializable Interface , Indicates that this class is serialized ,jdk Almost all encapsulated classes implement serialization (eg:String)- static Decorated properties cannot be serialized
- In addition to allowing programmers to communicate with programmers, version numbers , It doesn't work ( Serialization of version numbers can help programs avoid yellow lines , The rest is useless )
The data type of all attributes in the stored object must be implemented Serializable Interface ( polymerization : One class contains attributes with another class as the data type )- transient The modified attribute is called instantaneous attribute , Does not participate in serialization
Object flow can close its inner flow ( The underlying source code can be observed )- Used in conjunction with file streams ( Save or read object information and interact with local files - Similar to database )
because jdk The encapsulated classes are basically implemented Serializable Interface , Therefore, several objects can also be stored in the collection , Then the collection object is stored in the file through the object stream
eg: Object flow example
public static void main(String[] args) throws IOException, ClassNotFoundException {
// Save the object to a file
FileOutputStream fos=new FileOutputStream("E:\\person.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
Person person=new Person(" Zhang San ", 15);
oos.writeObject(person);
oos.close();// Object flow will close inner flow
// Read object information from file
FileInputStream fis=new FileInputStream("E:\\person.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Person p = (Person) ois.readObject();
ois.close();// Object flow will close inner flow
System.out.println(p);
}
3、 ... and 、 Character stream
characteristic : The smallest unit of transmission is char( character )
1. system :
The usage of the method provided by the byte stream parent class is similar
Reader( abstract class ): all
Character input streamParent class of
- read()
- read(char[] c)
- read(char[] c,int off, int len)
- close()
Writer( abstract class ): all
Character output streamParent class of
- write(int b)
- write(char[] c)
- write(char[] c, int off , int len)
- flush()
- close()
2. Subclass
- Conversion stream can convert byte stream to character stream
Four 、 file (File)
1.File Create objects
new File(“ route ”): This operation will not help us create a price folder , It refers to the file object that needs to be operated later
- Indicates the files and folders that can be operated ( Already exists : Delete file , Obtain the path and other operations )
- Indicates the file or folder to be operated ( Does not exist , About to create : Create folder )
---- The operation of files is realized through this step
2. Common properties and methods
Common properties :
- separator: Get the file separator of the current system
- pathSeparator: Get the path separator of the current system
Common methods :
- file object .getAbsolutePath(): Get the absolute path of the file
- file object .getPath() Get file path
- file object .getParent(): Get the path of the parent folder
- file object .getParentFile(): Get the corresponding file object
- file object .createNewFile();: create a file ( Files can only be created under the current program project , And src Same level )
- file object .mkdir(): establish 1 Level folder
- file object .mkdirs();: Create multi-level folders
- file object .isDirectory(): Determine whether it is a folder
- file object .isFile(): Determine if it's a document
- file object .exists(): Determine whether it is an executable program
- delete(): Delete files or first level empty folders
- length(): Get the number of bytes of content in the file
- listFiles(): Get all direct sub files or folders under the current folder
eg: Examples of common properties and methods
// new File(" file name "), It won't help us create price folders ,
// Need to call method , It refers to the current file object that needs to be operated later
File file = new File("E:\\text\\text01");
//1. Separator
String pathseparator = file.pathSeparator;
System.out.println(pathseparator);
System.out.println(file.separator);
//2. Get the absolute path of the file
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath);
//3. Get file path
String path = file.getPath();
System.out.println(path);
//4. Get the path of the parent folder
String parentPath = file.getParent();
System.out.println(parentPath);
//5. Get the corresponding File object
File parentFile = file.getParentFile();
System.out.println(parentFile.getAbsolutePath());
//6. create a file ( Files can only be created under the current program project , And src Same level )
File file2=new File("tx.txt");
file2.createNewFile();
//7. Relative to the path of the current program
File file3=new File("./b/c");
file3.mkdirs();
// Getting the path will be foolproof splicing :
//E:\Eclipse_Project\JavaBasic\.\b\c
System.out.println(file3.getAbsolutePath());
//8. Absolute path creates multi-level folders
File file4=new File("E:\\text\\test01\\b\\c\\t1.docx");
file4.mkdirs();
//9. Create a first level folder
File file5=new File("E:\\txt");
file5.mkdir();
//10. Judge the present file Whether the object is a file or folder
System.out.println(file5.isDirectory());
System.out.println(file5.isFile());
//11. Determine whether the current object is an executable program
File file6=new File("E:\\Eclipse_Project\\HelloWord.java");
System.out.println(file6.exists());
//12. Delete files or empty first level folders
file4.delete();
//13. Get the number of bytes of content in the current file
System.out.println(file6.length());
//14. Get all the execution sub files or folders under the current folder
File file7=new File("E:\\Eclipse_Project");
File[] listFiles = file7.listFiles();
for (File file8 : listFiles) {
System.out.println(file8.getName());
}
3. File filter
stay File There are two in the class listFiles Overloaded method , The parameters passed by the method can be filters
FileFilter:
- File[] listFiles(FileFilter filter)
- effect : Used to filter files (File object )
- Rewriting methods :accept(File dir, String name)
Parameters :File pathname: Use listFile Method to traverse the directory , Every file object obtainedFilenameFilter:
- File[] listFiles(FilenameFilter filter)
- effect : Used to filter file names
- Rewriting methods :accept(File dir, String name)
Parameters :dir: Corresponding to the parent folder File object name: The name of the current traversal fileBe careful : The two filter interfaces do not implement classes , We need to write our own implementation classes , then accept() Method overrides the filter rule . When accept The return value is true It indicates that the file is the file to be obtained , Otherwise, filter out the file
eg: Filter example
public static void main(String[] args) {
// TODO Auto-generated method stub
File file =new File("E:\\Eclipse_Project");
File[] files01=file.listFiles(new FileFilter() {
@Override
// The parameter is the currently traversed file object
public boolean accept(File pathname) {
String name = pathname.getName();
if (name.endsWith(".jpeg")) {
return true;
}
return false;
}
});
// Traverse
for (File file2 : files01) {
System.out.println(file2.getName());
}
/** * 1 ginseng : Corresponding to the parent folder File object * 2 ginseng : The name of the current traversal file */
File[] files02=file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
if (name.endsWith(".java")) {
System.out.println(dir.getName());
return true;
}
return false;
}
});
for (File file2 : files02) {
System.out.println(file2.getName());
}
}
5、 ... and 、Properties( class )
- Concept : Properties Class represents a set of persistent properties . Properties You can save to or load from the stream . Each in the attribute list
The key and its corresponding value are a string.- Inherit from collection : HashTable( class )
- Method :
1, Can be used as a configuration file , For example, it can be used with streams , Used for loading class objects ;(key=Value)2, Can be properties The file is read to the program through the stream Properties Object collection (list Method ), contrary , Can also be Properties Collection objects are saved to local files through streams (store)
边栏推荐
- 微信小程序的反编译
- JMM memory model concept
- Sword finger offer II 115: reconstruction sequence
- 吴恩达老师机器学习课程笔记 01 引言
- Embedding understanding + code
- Etcd principle
- Teacher Wu Enda's machine learning course notes 03 review of linear algebra
- CVPR2022Oral专题系列(一):低光增强
- Unity免费元素特效推荐
- Teacher wangshuyao's notes on operations research 05 linear programming and simplex method (concept, modeling, standard type)
猜你喜欢

leetcode-592:分数加减运算

Shallow reading of reentrantlock source code of abstractqueuedsynchronizer (AQS)

CVPR2022Oral专题系列(一):低光增强

vim文本编辑器的一些使用小技巧

LDAP brief description and unified authentication description

Teacher Wu Enda's machine learning course notes 02 univariate linear regression

新同事写了几段小代码,把系统给搞崩了,被老板爆怼一顿!

ECCV 2022丨轻量级模型架ParC-Net 力压苹果MobileViT代码和论文下载

Understanding of access, hybrid and trunk modes

How to write controller layer code gracefully?
随机推荐
模拟卷Leetcode【普通】172. 阶乘后的零
游戏资产的革命
Leetcode-1331: array ordinal conversion
阿里一面,给了几条SQL,问需要执行几次树搜索操作?
Software definition boundary SDP
数据库持久化+JDBC数据库连接
【冷冻电镜】Relion4.0——subtomogram教程
量子机器学习中的安全性问题
N2 interface of 5g control plane protocol
Teacher wangshuyao's notes on operations research 06 linear programming and simplex method (geometric significance)
数仓建模,什么是宽表?如何设计?好处与不足
数据库多表查询 联合查询 增删改查
联邦学习后门攻击总结(2019-2022)
【冷冻电镜|论文阅读】emClarity:用于高分辨率冷冻电子断层扫描和子断层平均的软件
【备忘】关于ssh为什么会失败的原因总结?下次记得来找。
MySQL:当你CRUD时BufferPool中发生了什么?十张图就能说清楚
Teacher Wu Enda's machine learning course notes 00 are written in the front
王树尧老师运筹学课程笔记 06 线性规划与单纯形法(几何意义)
吴恩达老师机器学习课程笔记 00 写在前面
吴恩达老师机器学习课程笔记 05 Octave教程




