当前位置:网站首页>【文件IO的简单实现】
【文件IO的简单实现】
2022-07-06 00:23:00 【DJL_new_life】
(点击跳转即可哦)
文件IO实例
复习
- 关于文件管理信息——File对象:文件系统树的遍历、增、删、改、查
- 输入、输出的模型
InputStream 读取数据流的设备。将输入设备抽象成数据流的源头
- 数据被抽象成流式(Stream)的形式
- 需要右内存空间,存放读取到的数据:一个变量的空间 或者一个数组的空间
- EOS : 表示数据已经被读完。 VS 本次暂时没有读到数据
- 可以将InputStream 接上其他的数据处理对象
OutputStream 将内存中的数据,通过写入数据流的设备,最终将数据写到输出设备中。
- 写的时候,为了同步内存和输出设备之间的写入速度差,一般是存在缓冲区(buffer)的。减少写的频次,提高写的速度
- 所以冲刷缓冲区(flush) 的 操作非常重要
- 字符集(ASCII 和 Unicode) 和字符集编码(ASCII、GBK、UTF-8)
1 给定路径,查找文件名中 包含指定的字符的文件列表,并根据用户的选择,决定是否删除
思路:
- 从一个树的根开始,遍历整颗树
- 将每个结点的名字 匹配 查找条件
- 如果符合条件,就保存File对象
- 遍历完成后,得到一组符合条件的File对象
- 一次询问用户,这些对象的下一步处理对象
package com.djl.io;
/** * 扫描指定目录,并找到名称中包含指定字符的所有普通文件(不包含目录),并且后续询问用户是否要 * 删除该文件 */
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("请输入要扫描的目录:");
String dir = sc.nextLine();
File file = new File(dir);
if(!file.isDirectory()){
System.out.println("要扫描的路径不是目录或者不存在");
return;
}
System.out.println("请输入文件名要包含的字符:");
String fileName = sc.nextLine();
Deque<File> list = new ArrayDeque<>();
//这个方法会把符合条件的文件路径存储到list中
findFile(file,fileName,list);
while (!list.isEmpty()){
File file1 = list.poll();
System.out.println("是否删除" + file1.getAbsolutePath() + " y/n");
String pd = sc.nextLine();
if(pd.toLowerCase().equals("y")){
file1.delete();
System.out.println("删除成功");
}
}
}
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 一个文件的复制
给定两个路径:源文件路径(必须存在)、目标路径(必须不存在 && 目录存在)
源文件 必须是普通文件,不是目录文件
思路:
- 由于只是进行复制,所以根本不考虑文件的内容具体是什么
- 所以我们要做的是:遍历(从源文件中读取数据,写入目标文件)直到所有的数据全部写完
package com.djl.io;
import java.io.*;
//文件的复制
public class Test2 {
public static void main(String[] args) throws Exception{
File oldFile = new File("D:/简历/Java开发工程师简历.docx");
File newFile = new File("D:/简历/2/简历.docx");
//统计复制需要的时间
long sta = System.currentTimeMillis();
//准备好的桶
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("复制时间是:"+s+"ms");
}
}
3 一个目录的复制
给定两个路径: 源文件路径 (必须存在 && 是目录)、目标路径(必须不存在 && 父目录存在)
思路:
if(目录) :继续递归 + 目标的相对位置创建目录
if(文件): 目标的相对位置,进行文件的复制
package com.djl.io;
//目录的复制
import java.io.*;
public class Test2_copyDir {
static File oldFile = new File("D:/简历");
static File newFile = new File("D:/简历/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("目录为空");
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();
}
}
}
}
要是对大家有所帮助的话,请帮我点个赞吧。
边栏推荐
- Mysql - CRUD
- Calculate sha256 value of data or file based on crypto++
- [binary search tree] add, delete, modify and query function code implementation
- Codeforces Round #804 (Div. 2)【比赛记录】
- Determinant learning notes (I)
- 【EI会议分享】2022年第三届智能制造与自动化前沿国际会议(CFIMA 2022)
- Atcoder beginer contest 258 [competition record]
- State mode design procedure: Heroes in the game can rest, defend, attack normally and attack skills according to different physical strength values.
- 【QT】Qt使用QJson生成json文件并保存
- Classic CTF topic about FTP protocol
猜你喜欢

Wechat applet -- wxml template syntax (with notes)

认识提取与显示梅尔谱图的小实验(观察不同y_axis和x_axis的区别)

FFMPEG关键结构体——AVCodecContext
![N1 # if you work on a metauniverse product [metauniverse · interdisciplinary] Season 2 S2](/img/f3/8e237296f5948dd0488441aa625182.jpg)
N1 # if you work on a metauniverse product [metauniverse · interdisciplinary] Season 2 S2

建立时间和保持时间的模型分析

FFMPEG关键结构体——AVFormatContext

XML配置文件

Key structure of ffmpeg -- AVCodecContext

Start from the bottom structure and learn the introduction of fpga---fifo IP core and its key parameters

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
随机推荐
Ffmpeg captures RTSP images for image analysis
Power query data format conversion, Split Merge extraction, delete duplicates, delete errors, transpose and reverse, perspective and reverse perspective
[EI conference sharing] the Third International Conference on intelligent manufacturing and automation frontier in 2022 (cfima 2022)
OS i/o devices and device controllers
STM32 configuration after chip replacement and possible errors
Notepad + + regular expression replace String
Multithreading and high concurrency (8) -- summarize AQS shared lock from countdownlatch (punch in for the third anniversary)
Data analysis thinking analysis methods and business knowledge - analysis methods (III)
MySql——CRUD
Single source shortest path exercise (I)
Power Query数据格式的转换、拆分合并提取、删除重复项、删除错误、转置与反转、透视和逆透视
Gd32f4xx UIP protocol stack migration record
uniapp开发,打包成H5部署到服务器
There is no network after configuring the agent by capturing packets with Fiddler mobile phones
AtCoder Beginner Contest 254【VP记录】
MySQL存储引擎
电机的简介
LeetCode 6006. Take out the least number of magic beans
MySQL functions
FFMPEG关键结构体——AVCodecContext