当前位置:网站首页>[simple implementation of file IO]
[simple implementation of file IO]
2022-07-06 00:32:00 【DJL_ new_ life】
( Click jump )
file IO example
review
- Information about document management ——File object : Traversal of file system tree 、 increase 、 Delete 、 Change 、 check
- Input 、 The output model
InputStream The device that reads the data stream . Abstract the input device into the source of data flow
- Data is abstracted into streaming (Stream) In the form of
- Need right memory space , Store the read data : The space of a variable Or the space of an array
- EOS : Indicates that the data has been read . VS No data has been read this time
- Can be InputStream Connect with other data processing objects
OutputStream Put the data in memory , By writing to the device of the data stream , Finally, write the data to the output device .
- When writing , To synchronize the write speed difference between memory and output device , Generally, there is a buffer (buffer) Of . Reduce the frequency of writing , Improve writing speed
- So scour the buffer (flush) Of Very important operation
- Character set (ASCII and Unicode) And character set encoding (ASCII、GBK、UTF-8)
1 Given path , Look in the file name A list of files containing the specified characters , And according to the user's choice , Decide whether to delete
Ideas :
- Start with the root of a tree , Traverse the whole tree
- Put the name of each node matching Search for conditions
- If you qualify , Just keep it File object
- After traversal , Get a group of qualified File object
- Ask the user once , The next step for these objects is to deal with objects
package com.djl.io;
/** * Scan the specified directory , And find all ordinary files whose names contain the specified characters ( Does not contain a directory ), And then ask the user whether to * Delete the file */
import java.io.File;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter the directory to scan :");
String dir = sc.nextLine();
File file = new File(dir);
if(!file.isDirectory()){
System.out.println(" The path to be scanned is not a directory or does not exist ");
return;
}
System.out.println(" Please enter the characters to be included in the file name :");
String fileName = sc.nextLine();
Deque<File> list = new ArrayDeque<>();
// This method will store the qualified file path to list in
findFile(file,fileName,list);
while (!list.isEmpty()){
File file1 = list.poll();
System.out.println(" Whether or not to delete " + file1.getAbsolutePath() + " y/n");
String pd = sc.nextLine();
if(pd.toLowerCase().equals("y")){
file1.delete();
System.out.println(" Delete successful ");
}
}
}
private static void findFile(File file, String fileName, Deque<File> list) throws Exception{
File[] files = file.listFiles();
if(files == null || files.length == 0){
return;
}
for(File f : files){
if(f.isDirectory()){
findFile(f,fileName,list);
}else {
String name = f.getName();
if(name.contains(fileName)){
list.offer(f);
}
}
}
}
}
2 Copy of a file
Given two paths : Source file path ( There must be )、 The target path ( Must not exist && Directory exists )
Source file It must be an ordinary file , Not a directory file
Ideas :
- Because it's just copying , So we don't consider the content of the document at all
- So what we have to do is : Traverse ( Read data from the source file , Write target file ) Until all the data are written
package com.djl.io;
import java.io.*;
// Copy of documents
public class Test2 {
public static void main(String[] args) throws Exception{
File oldFile = new File("D:/ resume /Java Resume of Development Engineer .docx");
File newFile = new File("D:/ resume /2/ resume .docx");
// Count the time required for replication
long sta = System.currentTimeMillis();
// Prepared bucket
byte[] bur = new byte[1024];
int count = 0;
try (InputStream is = new FileInputStream(oldFile)){
try(OutputStream os = new FileOutputStream(newFile)){
while (true){
int n = is.read(bur);
count += n;
if(n == -1){
break;
}
os.write(bur);
}
os.flush();
}
}
long end = System.currentTimeMillis();
long ms = end-sta;
double s = ms/1000.0;
System.out.println(" Copy time is :"+s+"ms");
}
}
3 Copy of a directory
Given two paths : Source file path ( There must be && Is a directory )、 The target path ( Must not exist && The parent directory does not exist )
Ideas :
if( Catalog ) : Continue to recursive + Create a directory relative to the target
if( file ): The relative position of the target , Copy files
package com.djl.io;
// Copy of directory
import java.io.*;
public class Test2_copyDir {
static File oldFile = new File("D:/ resume ");
static File newFile = new File("D:/ resume /2");
public static void main(String[] args) throws Exception{
traversal(oldFile);
}
private static void traversal(File oldFile) throws Exception{
File[] oldFiles = oldFile.listFiles();
if(oldFiles == null){
System.out.println(" The directory is empty ");
return;
}
for(File file : oldFiles){
String oldFilePath = oldFile.getCanonicalPath();
String filePath = file.getCanonicalPath();
String newFilePath = newFile.getCanonicalPath();
String rever = filePath.substring(oldFilePath.length());
newFilePath = newFilePath + rever;
File oneNewFile = new File(newFilePath);
if(file.isDirectory()){
oneNewFile.mkdir();
traversal(file);
}else if(file.isFile()){
copyFile(file,oneNewFile);
}
}
}
private static void copyFile(File file, File oneNewFile) throws Exception{
try(InputStream is = new FileInputStream(file)){
try(OutputStream os = new FileOutputStream(oneNewFile)){
while (true){
byte[] bur = new byte[1024];
int n = is.read(bur);
if(n == -1){
break;
}
os.write(bur);
}
os.flush();
}
}
}
}
If it helps you , Please give me a compliment .
边栏推荐
- Hudi of data Lake (2): Hudi compilation
- 数据分析思维分析方法和业务知识——分析方法(三)
- 认识提取与显示梅尔谱图的小实验(观察不同y_axis和x_axis的区别)
- AtCoder Beginner Contest 254【VP记录】
- The global and Chinese markets of dial indicator calipers 2022-2028: Research Report on technology, participants, trends, market size and share
- FPGA内部硬件结构与代码的关系
- AtCoder Beginner Contest 258【比赛记录】
- MySQL global lock and table lock
- 如何利用Flutter框架开发运行小程序
- FFmpeg抓取RTSP图像进行图像分析
猜你喜欢

OS i/o devices and device controllers

LeetCode 1189. Maximum number of "balloons"

Leetcode 450 deleting nodes in a binary search tree

There is no network after configuring the agent by capturing packets with Fiddler mobile phones

Location based mobile terminal network video exploration app system documents + foreign language translation and original text + guidance records (8 weeks) + PPT + review + project source code

Common API classes and exception systems

Permission problem: source bash_ profile permission denied

Room cannot create an SQLite connection to verify the queries
![[noi simulation] Anaid's tree (Mobius inversion, exponential generating function, Ehrlich sieve, virtual tree)](/img/d6/c3128e26d7e629b7f128c551cd03a7.png)
[noi simulation] Anaid's tree (Mobius inversion, exponential generating function, Ehrlich sieve, virtual tree)

Configuring OSPF load sharing for Huawei devices
随机推荐
如何制作自己的机器人
Yolov5, pychar, Anaconda environment installation
Calculate sha256 value of data or file based on crypto++
Search (DFS and BFS)
An understanding of & array names
MDK debug时设置数据实时更新
Global and Chinese market of valve institutions 2022-2028: Research Report on technology, participants, trends, market size and share
FFmpeg抓取RTSP图像进行图像分析
Codeforces gr19 D (think more about why the first-hand value range is 100, JLS yyds)
Idea远程提交spark任务到yarn集群
Atcoder beginer contest 258 [competition record]
认识提取与显示梅尔谱图的小实验(观察不同y_axis和x_axis的区别)
MySql——CRUD
从底层结构开始学习FPGA----FIFO IP核及其关键参数介绍
Multithreading and high concurrency (8) -- summarize AQS shared lock from countdownlatch (punch in for the third anniversary)
NLP generation model 2017: Why are those in transformer
LeetCode 6005. The minimum operand to make an array an alternating array
7.5 decorator
Notepad + + regular expression replace String
FFMPEG关键结构体——AVFormatContext