P2-7 案例:整理视频文件夹

案例:整理视频文件夹


需求说明

需求说明1

思路
1.先把文件夹中所有MP4的文件读取出来
2.分别取目录的名字+ ”-“ + 文件名
3.整理后拷贝到其他的文件夹:output文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//杨中科老师的写法
File file = new File("E:/test");
File[] dirs = file.listFiles();
for(File dir : dirs)//先遍历文件夹
{
for(File fileMp4 : dir.listFiles())//再遍历文件夹下的文件
{
//System.out.println(fileMp4);
String filePath = fileMp4.getPath();//把File转换为字符串,方便用split等方法
//System.out.println(filePath);
filePath = filePath.replace("\\","/");//把\替换为/,
//// 这样无论是Windows还是其他操作系统,这样路径分隔符都同意为/
String[] strs = filePath.split("/");
//System.out.println(Arrays.toString(strs));
String folderName = strs[strs.length-2];//倒数第1个是文件夹的名字
String fileName = strs[strs.length-1];//倒数第0个是文件的名字
String outputFileName = "e:/temp/output/"+folderName+"-"+fileName;//目标文件名
//System.out.println(outputFileName);
byte[] bytes = IOHelpers.readAllBytes(fileMp4);//文件内容
IOHelpers.writeAllBytes(outputFileName,bytes);//写入新文件
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//自己的写法
String[] strs = IOHelpers.getFilesRecursively("D:/JavaTest1","mp4");

for (String str:strs)
{
String strs1 = str.replace("\\","/");//把\替换为/
// 这样无论是Windows还是其他操作系统,这样路径分隔符都同意为/
String[] strs2 = strs1.split("/");
String name = strs2[strs2.length-2];//倒数第1个是文件夹的名字
String filename = strs2[strs2.length-1];//倒数第0个是文件的名字
String outputFileName = "D:/JavaTest1/output/"+name+"-"+filename;
byte[] bytes = IOHelpers.readAllBytes(str);//文件内容
IOHelpers.writeAllBytes(outputFileName,bytes);//写入新文件
}

练习

Snipaste_2024-08-05_21-25-19

思路
1.先找出文件夹下的mp3歌曲
2.用、去分割歌曲名称
3.然后用-去分为两半,前面是歌手的名字去作为文件夹,后面作为歌曲的名字,放在文件夹之下
4.然后读取对应的内容,拷贝到新文件夹中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//先遍历出文件夹下所有的mp3歌曲
String[] strs= IOHelpers.getFilesRecursively("E:/KwDownload/song","mp3");

for (String fileMp3:strs)
{
//把\替换成/
//这样无论是Windows还是其他操作系统,路径分隔符统一都为/
String filePath = fileMp3.replace("\\","/");
String[] strs2 = filePath.split("/");//用/去分割,然后获取到MP3的文件名
String filename = strs2[strs2.length-1];
String [] strs3 =filename.split("、");//用、去分割歌曲前面的顺序,然后获取到MP3的歌手+文件名
String newfilename = strs3[strs3.length-1];
String [] strs4 =newfilename.split("-");//用-去分割MP3的歌手和歌名
String name = strs4[strs4.length-2];//歌手名字
String MP3 = strs4[strs4.length-1];//歌曲名
String outputFileName = "D:/JavaTest1/output/"+name+"/"+MP3;//加+把对应的歌曲归到对应的歌手文件夹下面去
byte[]bytes = IOHelpers.readAllBytes(fileMp3);//拷贝文件
IOHelpers.writeAllBytes(outputFileName,bytes);//写入在对应的路径下面去
}

P2-7 案例:整理视频文件夹
http://example.com/2024/08/06/SE101-零基础玩Java/Part2-笔记/P2-7 案例:整理视频文件夹/
Author
John Doe
Posted on
August 6, 2024
Licensed under