Java代码修改文件后缀名(迭代)

缘由

老师让写一个修改后缀名的作业,题目:在一个文件夹内 把所有的JPG文件按照image1.JPEG……的格式改名存储。后来他又要求了将要修改的文件复制到一个新的文件夹中,这样可以做到不影响源文件夹。所以我就做了两个版本,当然,其中很多方法都是在网上搜寻的,所以并不是很了解,只是单纯的实现了。

版本一:在当前文件夹中改名

package com.hist.two;

import java.io.File;
import java.util.Scanner;

/**
 * @author gky
 * @date 2023/3/15
 * @apiNote 在一个文件夹内 把所有的JPG文件按照image1.JPEG……的格式改名存储
 */
public class ReName {
    /**
     * TODO:修改文件名的方法
     *
     * @param path
     * @return
     * @author gky
     * @date 2023/3/15
     */
    public static void getNew(String path) {
        File file = new File(path);
        //返回一个字符串数组,得到文件夹下的所有文件和文件夹
        String[] list = file.list();

        //如果该文件夹存在且不为空
        if (list != null && list.length > 0) {
            for (String oldName : list) {
                File oldFile = new File(path, oldName);
                //判断是文件还是文件夹
                if (!oldFile.isDirectory()) {
                    //是文件则判断是不是要修改的
                    if (oldName.contains(".jpg")) {
                        System.out.print("修改前名称:" + oldName + "\t");
                        String newName = oldName.substring(0, oldName.lastIndexOf(".")) + ".jpeg";
                        System.out.println("修改后名称:" + newName);
                        File newFile = new File(path, newName);
                        //重命名这个路径的文件
                        boolean flag = oldFile.renameTo(newFile);
                        //修改成功返回true,否则返回false
                        System.out.println(flag);
                    }
                } else {
                    //是文件夹则进行迭代
                    String newPath = path + "/" + oldName;
                    getNew(newPath);
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要修改文件夹的绝对路径:");
        String path = sc.nextLine();
        getNew(path);
    }
}

版本二:将一个文件夹中的所有jpg文件复制到一个新的文件夹,并将文件后缀名改为jpeg

package com.hist.two;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

/**
 * @author gky
 * @date 2023/04/12
 * @apiNote 将一个文件夹中的所有jpg文件复制到一个新的文件夹,并将文件后缀名改为jpeg
 */
public class ReName2 {
    /**
     * 复制文件的方法
     *
     * @param
     */
    public static void copyfile(String oldPath, String newPath) throws IOException {
        FileChannel sourceFile = null;
        FileChannel copiedFile = null;

        File file = new File(oldPath);
        //返回一个字符串数组,得到文件夹下的所有文件和文件夹
        String[] list = file.list();

        //如果该文件夹存在且不为空
        if (list != null) {
            for (String childName : list) {
                File oldFile = new File(oldPath, childName);
                //判断是文件还是文件夹
                if (!oldFile.isDirectory()) {
                    //是文件则判断是不是要复制的的
                    if (childName.contains(".jpg")) {
                        try {
                            sourceFile = new FileInputStream(oldFile).getChannel();
                            copiedFile = new FileOutputStream(newPath + "/" + childName.substring(0, childName.lastIndexOf(".")) + ".jpeg").getChannel();
                            /**
                             * 参数一:原通道 参数二:文件中开始传输的位置 参数三:要传输的最大字节数
                             */
                            copiedFile.transferFrom(sourceFile, 0, sourceFile.size());
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            sourceFile.close();
                            copiedFile.close();
                        }

                    }
                } else {
                    //是文件夹则进行迭代
                    String nextPath = oldPath + "/" + childName;
                    copyfile(nextPath, newPath);
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要修改文件夹的绝对路径:");
        String oldPath = sc.nextLine();
        System.out.println("请输入要创建新文件夹的目录:");
        //用于储存jpeg文件
        String newPathStr = sc.nextLine();
        /**
         * Path:可用于在文件系统中定位文件的对象。它通常表示一个系统相关的文件路径。
         * createDirectories:通过首先创建所有不存在的父目录来创建目录。与createDirectory方法不同,如果目录已经存在而无法创建,则不会抛出异常。
         * Path.get():将路径字符串或连接形成路径字符串的字符串序列转换为path。
         */
        Path newPath = Files.createDirectories(Paths.get(newPathStr));
        String pathName = newPath.toString();
        System.out.println("新文件夹创建成功,名称为:" + pathName);
        //将旧文件夹中的所有jpg文件复制到一个新文件夹
        copyfile(oldPath, pathName);
        System.out.println("文件名修改成功!");

    }
}

总结

其中版本二创建新文件夹用到了Path,可以返回路径。复制文件到新文件夹用到了FileChannel,相比于传统的输入输出流,传输速度更快,稳定性更高。并且FileOutputStream()可以间接的在复制文件的时候就把文件名改了,省去了版本一改文件名的步骤。变量命名有点乱,见谅。(idea提示我 list.length > 0是多余的,有大佬能解释一下吗?)。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值