当前位置:网站首页>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();
}
}
}
}边栏推荐
- 程序分析与优化 - 9 附录 XLA的缓冲区指派
- An excellent orm in dotnet circle -- FreeSQL
- Nc50528 sliding window
- Sentry developer contribution Guide - configure pycharm
- 1.12 - 指令
- Is there a free text to speech tool to help recommend?
- Helm basic learning
- Program analysis and Optimization - 9 appendix XLA buffer assignment
- 文件操作IO-Part2
- 【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
猜你喜欢

University of Toronto:Anthony Coache | 深度强化学习的条件可诱导动态风险度量

ftrace工具的介绍及使用

Use Jenkins II job

Vulkan-性能及精细化

如何系统学习机器学习

Automated defect analysis in electronic microscopic images

Why is the website slow to open?

How SQLSEVER removes data with duplicate IDS

【AutoSAR 七 工具链简介】

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
随机推荐
MySQL 23 classic interview hanging interviewer
2022上半年值得被看见的10条文案,每一句都能带给你力量!
【AutoSAR 六 描述文件】
Attributeerror: 'tuple' object has no attribute 'layer' problem solving
antv x6节点拖拽到画布上后的回调事件(踩大坑记录)
[pulsar document] concepts and architecture
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
ftrace工具的介绍及使用
Introduction and use of ftrace tool
Form form instantiation
JSON转换工具类
Andorid gets the system title bar height
Markdown tutorial
Wechat applet obtains the information of an element (height, width, etc.) and converts PX to rpx.
多进程编程(二):管道
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
form表单实例化
Nc50528 sliding window
redis21道经典面试题,极限拉扯面试官
node_modules删不掉