欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java批量修改文件后缀名方法总结

程序员文章站 2023-12-20 08:02:45
突然需要改一堆文件的后缀名,所以想编程解决,话不多说直接上代码 java import java.io.file; import java.util.sc...

突然需要改一堆文件的后缀名,所以想编程解决,话不多说直接上代码

java

import java.io.file;

import java.util.scanner;

 

public class fileedit {

 

 public static void renamefiles(string path, string oldext, string newext) {

  file file = new file(path);

  if (!file.exists()) {

   system.err.println("文件路径不存在!");

   return;

  }

  file[] files = file.listfiles();

  if (files.length <= 0) {

   system.err.println("当前路径文件不存在!");

   return;

  }

  for (file f : files) {

   if (f.isdirectory()) {

    renamefiles(f.getpath(), oldext, newext);

   } else {

    string name = f.getname();

    if (name.endswith("." + oldext)) {

     name = name.substring(0, name.lastindexof(".") + 1);

     name += newext;

     f.renameto(new file(f.getparent() + "\\" + name));

    }

   }

  }

 }

 

 public static void main(string[] args) {

  scanner sc = new scanner(system.in);

  system.out.println("请输入要修改文件后缀名的文件夹:");

  string path = sc.nextline();

  system.out.println("请输入修改前的后缀名:");

  string oldext = sc.nextline();

  system.out.println("请输入修改后的后缀名:");

  string newext = sc.nextline();

 

  renamefiles(path, oldext, newext);

  system.out.println("操作完成");

 }

}

其他方法

在网上查了下,发现还有cmd命令可以解决,比如将txt后置改为7z,那么在你需要修改的目录运行cmd然后输入命令ren *.txt *.rar,就可以将所有txt结尾的文件进行修改;此外可以将本命令保存为bat脚本文件,双击进行运行。

ren *.jpg *.txt

就可以将目录下所有的.jpg文件修改成.txt文件

java批量修改文件后缀名方法总结

效果如下:

java批量修改文件后缀名方法总结

方式2
也可以使用bat脚本的方式,如下图中ren.bat脚本中的内容,就是上面敲的命令:

java批量修改文件后缀名方法总结

修改的方式应该还有很多吧

上一篇:

下一篇: