练习:
1、利用File实现递归删除,写死。(删除从键盘输入的后缀名文件)
2、统计工作空间下Java文件,并输出代码行数
3、复制文件
package day1106;import java.io.*;
import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;
import java.util.Locale;
import java.util.Scanner;public class Demo02 {private static int number;private static long Count = 0;public static void main(String[] args) throws IOException {Scanner sc = new Scanner(System.in);do {System.out.println("请输入一个需要执行的序号:" + "\n" + "\t" + "1:删除文件" + "\n" + "\t" + "2:统计java文件" + "\n" + "\t" + "3:复制文件" + "\n" + "\t" + "4:退出");number = sc.nextInt();switch (number) {/*** 退出系统*/case 4:System.out.println("已退出!");break;/*** 删除文件*/case 1:Scanner scanner = new Scanner(System.in);System.out.println("请输入要删除的文件后缀名(不用加.):");String deletef = scanner.nextLine();deleteFilesdeletef(new File("G:/test/Dele/day1029"),deletef);System.out.println("所有后缀名为"+deletef+"的文件删除完成");//scanner.close();break;/*** 统计Java文件并输出代码行数*/case 2:Path rootPath = Paths.get("G:/test");Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {@Overridepublic FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {if (file.toString().endsWith(".java")) {Count += Files.lines(file).count();}return FileVisitResult.CONTINUE;}});System.out.println("代码行数: " + Count);break;/*** 复制文件*/case 3:Path sourcePath = Paths.get("G:/shixun/test/src/cn/hxzy/pro/Demo01.java"); // 源文件路径Path destinationPath = Paths.get("G:/test/Dele/copytest/thistest.java"); // 目标文件路径try {Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);System.out.println("文件复制成功!");} catch (IOException e) {System.out.println("文件复制失败: " + e.getMessage());}break;default:System.out.println("输入无效,请重新输入一个正确的序号!");break;}} while (number != 4);}/*** 删除* @param*/public static void deleteFilesdeletef(File directory,String deletef) {File[] files = directory.listFiles();//File[] files = directory.listFiles((f) -> f.isFile() && f.getName().endsWith(i)); // 判断是否为.png文件if (files != null) {for (File file : files) {if (file.isDirectory()) {deleteFilesdeletef(file, deletef);}else {if (file.getName().toLowerCase(Locale.ROOT).endsWith("."+deletef)){boolean deleted =file.delete();if (!deleted){System.out.println("删除文件失败: " + file.getAbsolutePath());}}}}}}
}
练习:
通过字节输入和输出流实现将视频文件进行复制。
package day1106;import java.io.*;public class Demo03 {public static void main(String[] args) {/*** 通过字节输入和输出流实现将视频文件进行复制。*/try {// 源视频文件路径String Sourcepath = "https://files.youth.cn/video/zq_video/202411/P020241107344980818272.mp4";// 目标视频文件路径String Targetpath = "G:/test/Dele/测试/day1104";FileInputStream fis = new FileInputStream(Sourcepath);FileOutputStream fos = new FileOutputStream(Targetpath);byte[] buffer = new byte[1048576];int length;while ((length = fis.read(buffer)) != -1) {fos.write(buffer, 0, length);}fis.close();fos.close();System.out.println("视频复制成功!");} catch (IOException e) {System.out.println("发生错误:" + e.getMessage());}}
}