当前位置:网站首页>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();
}
}
}
}边栏推荐
- mm中的GAN模型架构
- Redis21 classic interview questions, extreme pull interviewer
- University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
- 【日常训练】871. 最低加油次数
- 如何系统学习机器学习
- About qbytearray storage hexadecimal and hexadecimal conversion
- logback配置文件
- 关于Unity屏幕相关Screen的练习题目,Unity内部环绕某点做运动
- Shell implements basic file operations (cutting, sorting, and de duplication)
- 【雅思阅读】王希伟阅读P2(阅读填空)
猜你喜欢

详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图

可下载《2022年中国数字化办公市场研究报告》详解1768亿元市场

pageoffice-之bug修改之旅

1.11 - 总线

【单片机项目实训】八路抢答器

Use Jenkins II job

Rust所有权(非常重要)

University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement

2022中国3D视觉企业(引导定位、分拣场景)厂商名单

文件操作IO-Part2
随机推荐
Automated defect analysis in electron microscopic images-论文阅读笔记
如何系统学习机器学习
Unity learns from spaceshooter to record the difference between fixedupdate and update in unity for the second time
Multi process programming (III): message queue
利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度
About qbytearray storage hexadecimal and hexadecimal conversion
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
kubernetes编写yml简单入门
cordova-plugin-device获取设备信息插件导致华为审核不通过
简单聊聊运维监控的其他用途
Introduction of UART, RS232, RS485, I2C and SPI
1.11 - bus
Preview word documents online
【AutoSAR 九 C/S原理架构】
【单片机项目实训】八路抢答器
奥斯陆大学:Li Meng | 基于Swin-Transformer的深度强化学习
An excellent orm in dotnet circle -- FreeSQL
[IELTS reading] Wang Xiwei reading P1 (reading judgment question)
Hdu3507 (slope DP entry)
University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement