当前位置:网站首页>File operation io-part2
File operation io-part2
2022-07-03 00:43:00 【Gold content of Xiaobai】
Catalog
How to modify the file tree structure
Determine whether there is a method
Judge that the file exists && It's a folder.
Judge that the file exists && It's an ordinary document
Return the general absolute path of the file
Return the standard absolute path of the file
Get the filename ( Current filename , No path other information )
Get the parent class file name
Get the time when the file was last modified
All children who get the document
Where is the working directory of the process runtime ?
About the reading and writing of content —— About reading
Read the classes and models used in the file
Use byte Input method of array —— read(byte[] b)
Direct reception ——read() Method
utilize InputStream Direct reading of binary data
String Construction method of ( Not recommended )
About the reading and writing of content —— About what's written
buffer —> Balanced write speed
How to operate the file
Key method
Construction method
You can use absolute paths and relative paths , But I usually use the absolute path .
File file = new File("C:\\Users\\DELL\\Desktop\\exercise");
How to modify the file tree structure
Create new file method
file.createNewFile();
Create directory
All nonexistent directories under this path will be created
file.mkdirs();
Delete file method
file.delete();
Mobile nodes ( rename )
File file = new File("D:\\ Course \\2022-06-29-2022 Rocket class -IO\\src\\nihao.txt");
File dest = new File("D:\\ Course \\2022-06-29-2022 Rocket class -IO\\src\\bye.txt");
// This directory will realize the cutting effect , The files in the original directory will be moved to the new directory
//File dest = new File("D:\\ Course \\2022-06-29-2022 Rocket class -IO\\dest\\nihao.txt");
file.renameTo(dest);
Determine file properties
Determine whether there is a method
file.exists()
Judge that the file exists && It's a folder.
file.isDirectory();
Judge that the file exists && It's an ordinary document
file.isFile();
Get file standard path
Return the general absolute path of the file
String absolutePath = file.getAbsolutePath();
Return the standard absolute path of the file
String canonicalPath = file.getCanonicalPath();
For catalog
file.listFiles();
Traverse this path
It is generally used for the overall deletion of directory folders
Only depth traversals are listed here , Breadth traversal requires the help of queues .
private static void traversalDepthFirst(File dir) throws Exception {
// 1. Find all the children in this directory
File[] files = dir.listFiles();
if (files == null) {
return;
}
// 2. For every child , Determine whether it is a directory or a file
for (File file : files) {
if (file.isDirectory()) {
// If it is a directory , Then continue to recursively traverse the processing
System.out.println("[D] " + file.getCanonicalPath());
traversalDepthFirst(file);
} else {
System.out.println("[F] " + file.getCanonicalPath());
}
}
}
Get the file name method
Get the filename ( Current filename , No path other information )
file.getName();
Get the parent class file name
// Get the parent class file name
file.getParent();
// Want to get the standard writing , You need to get the parent file first , Then get the standard absolute path .
String ret = file.getParentFile().getCanonicalPath();
Get the time when the file was last modified
file.lastModified();
All children who get the document
File[] files = file.listFiles();
Relative paths
About relative paths , It needs to be clear
Where is the working directory of the process runtime ?
working directory :current working diretory(cwd)
stay JVM The following is usually the directory when the process starts .
That is to say, your idea The startup directory is where the folder is placed
About the reading and writing of content —— About reading
There are two ways to read :
1). Direct reading ( Read as binary data , That's in the code byte In units of );
2). Text reading
Read the classes and models used in the file
1. Input stream
When reading a document , We use it java.io.InputStream Input as an input stream .
2. Use concrete classes
InputStream It's an abstract class , We use subclasses FileInputStream File input .
3. About abstract models
The input process can be represented by a model , We can think of the input stream we build as a tap , The file we need to input is regarded as a water tower , Last , We also need a bucket to catch the water from the water tower flowing through the faucet .
Water tower : Specific documents
water tap :FileInputStream class
Buckets :byte[] Array
4. Remember to turn off
Remember to turn off the tap after you use it
The specific methods
We use FileInputStream Class read() Method to carry the input stream
Turn off the signal
We use... In our code -1 To express EOS( Turn off the signal )
Use byte Input method of array —— read(byte[] b)
This method will return how much water it received .
This method can receive a lot of water at a time , We just need to pick up the water in the bucket , Take another container that just can hold this water and put it in , Then traverse the container .
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream("./hello.txt");
// FileInputStream I can assign a value to InputStream, Because There is an inheritance relationship && FileInputStream yes InputStream Child class of
// Prepare a bucket
byte[] buf = new byte[1024]; // 1024 The representative can answer 1024 drop ( byte ) water , We have the capacity of the barrel ready
// Take the prepared bucket to the tap to collect water
int n = is.read(buf);
// there n Represents how many drops we really received this time ( byte ) water
// n Must be less than or equal to 1024 && n >= 0
// System.out.println(n); // 28
// Real data on buf from [0, 28)
byte[] bytes = Arrays.copyOf(buf, n);
for (byte b : bytes) {
System.out.printf("%02x\n", b);
}
is.close();
}
Direct reception ——read() Method
This method directly catches every drop of water flowing through the tap , No buckets and containers , There is no water to return int The value will change to -1, At this time, it is necessary to quit the water connection process and turn off the tap .
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream("./hello.txt");
while (true) {
int data = is.read();
if (data == -1) {
// All the data has been read
break;
}
// otherwise ,data It's the data we get
byte b = (byte) data;
System.out.printf("%02x\n", b);
}
is.close();
}
utilize InputStream Direct reading of binary data
String Construction method of ( Not recommended )
May adopt String The construction method of... Can be byte[] The array is directly converted to the text in the text file .
Put it into the code , There's no need to do it again byte Array traversal , But directly byte Just pass in the array
try (InputStream is = new FileInputStream("./hello.txt")) {
byte[] buf = new byte[1024];
int n = is.read(buf);
// System.out.println(n);
// for (int i = 0; i < n; i++) {
// System.out.printf("%02x ", buf[i]);
// }
String s = new String(buf, 0, n, "UTF-8");
System.out.println(s);
}
utilize Scanner Method
We can use Scanner Method , Direct will Scanner Compared to a bucket , The input stream goes directly into Scanner that will do
Scanner In fact, we also need close, So add one try It's just that we don't close it at ordinary times .
try (InputStream is = new FileInputStream("./hello.txt")) {
try (Scanner scanner = new Scanner(is, "UTF-8")) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine(); // Line breaks are removed by default
System.out.println("|" + line + "|");
}
}
}
About the reading and writing of content —— About what's written
buffer —> Balanced write speed
Writing content is actually through data through memory to hard disk , Because the writing speed of memory is much faster than that of hard disk ,
We need one “ buffer buffer” To balance the difference in speed .
Buffer flushing
Flushing the buffer is to flush the data in the buffer into the hard disk . The following situations will cause disk brushing :
1. The buffer is full or reaches a certain threshold .
2. Time between reaching
3. The process takes the initiative to brush the disk
Before closing
There will still be some data left in memory , At this time, all the data will be flushed into the hard disk through a flushing .
In the use of OutputStreamWriter Implement class time , Pay attention to the last use .flush() To flush the data in the buffer .
OutputStreamWriter
We use Writer Subclasses of OutputStreamWriter To complete the write operation .
This step is to Do character set encoding
public static void main1(String[] args) throws Exception {
try (OutputStream os = new FileOutputStream("./world.txt")) {
try (Writer writer = new OutputStreamWriter(os, "UTF-8")) {
writer.write(" Hello China \r\n");
writer.write(" It's nothing ");
writer.flush();
}
}
}
PrintWriter
coordination PrintWriter, And its construction method is introduced writer Object can It's similar to print Effect of the method .
public static void main(String[] args) throws Exception {
try (OutputStream os = new FileOutputStream("./world.txt")) {
try (Writer writer = new OutputStreamWriter(os, "UTF-8")) {
try (PrintWriter printWriter = new PrintWriter(writer)) {
printWriter.println(1 + 1);
printWriter.print(3);
printWriter.printf("%s + %d", " I ", 3);
printWriter.flush();
}
}
}
}
边栏推荐
- 多进程编程(五):信号量
- form表单实例化
- 1.12 - Instructions
- NC17059 队列Q
- Multiprocess programming (4): shared memory
- Feature Engineering: summary of common feature transformation methods
- Multiprocess programming (II): Pipeline
- [jetcache] jetcache configuration description and annotation attribute description
- 【Pulsar文档】概念和架构/Concepts and Architecture
- Vulkan并非“灵药“
猜你喜欢
2022中国3D视觉企业(引导定位、分拣场景)厂商名单
可下载《2022年中国数字化办公市场研究报告》详解1768亿元市场
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
Win10 多种方式解决无法安装.Net3.5的问题
【AutoSAR 九 C/S原理架构】
【AutoSAR 五 方法论】
多进程编程(一):基本概念
Basic use of shell script
Automated defect analysis in electronic microscopic images
Shell implements basic file operations (cutting, sorting, and de duplication)
随机推荐
lex && yacc && bison && flex 配置的问题
文件操作IO-Part2
【AutoSAR 五 方法论】
Is there a free text to speech tool to help recommend?
Explain in detail the significance of the contour topology matrix obtained by using the contour detection function findcontours() of OpenCV, and how to draw the contour topology map with the contour t
The "2022 China Digital Office Market Research Report" can be downloaded to explain the 176.8 billion yuan market in detail
There is an unknown problem in inserting data into the database
FAQ | FAQ for building applications for large screen devices
字符设备注册常用的两种方法和步骤
Shell 实现文件基本操作(切割、排序、去重)
线程的启动与优先级
【JetCache】JetCache的配置说明和注解属性说明
cordova-plugin-device获取设备信息插件导致华为审核不通过
node_modules删不掉
Set up nacos2 X cluster steps and problems encountered
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
Rust字符串切片、结构体和枚举类
redis21道经典面试题,极限拉扯面试官
Rust所有权(非常重要)
Problèmes de configuration lex & yacc & Bison & Flex