好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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

java

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

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脚本文件,双击进行运行。

?

1

ren *.jpg *.txt

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

效果如下:

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

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

查看更多关于java批量修改文件后缀名方法总结的详细内容...

  阅读:15次