本文實例講述了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
86
87
88
89
90
91
|
package sys.file; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.*; public class ZReName { public static void main(String args[]) { ZReName r = new ZReName(); r.replace(); //r.changeOrder(); } public void replace (){ File dir = new File( "G://電影//那年那兔那些事兒[原畫版]" ); // 這里寫上發替換的文件夾路徑,注意使用雙斜杠 String[] files = dir.list(); File f = null ; String filename = "" ; //String oldName = "[電影天堂www.dygod.cn]"; String oldName = "" ; //名稱中要替換的部分 String newName = "" ; //名稱中要替換成的樣子,為空時即為刪除 for (String file : files) { f = new File(dir, file); // 注意,這里一定要寫成File(fl,file)如果寫成File(file)是行不通的,一定要全路徑 filename = f.getName(); System.out.println(filename); String S1= "\\d{4}.(優酷網|搜狐視頻)-" ; ZReName r = new ZReName(); boolean b = r.regex1(S1, filename); oldName = r.regex(S1, filename); if (b){ //f.renameTo(new File(fl.getAbsolutePath()+"//"+filename.replace("要替換掉的內容","替換成的內容"))); //這里可以反復使用replace替換,當然也可以使用正則表達式來替換了 // 這里可以反復使用replace替換,當然也可以使用正則表達式來替換了 f.renameTo( new File(dir.getAbsolutePath() + "//" + filename.replace(oldName, newName))); //將前X位刪除 //f.renameTo(new File(dir.getAbsolutePath() + "//"+ filename.substring(9))); } } System.exit( 0 ); } public void changeOrder (){ File dir = new File( "G://合并" ); // 這里寫上發替換的文件夾路徑,注意使用雙斜杠 String[] files = dir.list(); File f = null ; String filename = "" ; //String oldName = "[電影天堂www.dygod.cn]"; String oldName = "" ; //名稱中要替換的部分 String newName = "" ; //名稱中要替換成的樣子,為空時即為刪除 for (String file : files) { f = new File(dir, file); // 注意,這里一定要寫成File(fl,file)如果寫成File(file)是行不通的,一定要全路徑 filename = f.getName(); System.out.println(filename); String S1= "\\d+" ; ZReName r = new ZReName(); boolean b = r.regex1(S1, filename); oldName = filename; newName = r.regex(S1, filename)+ " " +filename; if (b){ //f.renameTo(new File(fl.getAbsolutePath()+"//"+filename.replace("要替換掉的內容","替換成的內容")));//這里可以反復使用replace替換,當然也可以使用正則表達式來替換了 // 這里可以反復使用replace替換,當然也可以使用正則表達式來替換了 f.renameTo( new File(dir.getAbsolutePath() + "//" + filename.replace(oldName, newName))); //將前X位刪除 //f.renameTo(new File(dir.getAbsolutePath() + "//"+ filename.substring(9))); } } System.exit( 0 ); } //S1要查找的正則表達式,S2查找源 public String regex(String S1,String S2){ Pattern p = Pattern.compile(S1); Matcher m = p.matcher(S2); boolean result = m.find(); //System.out.println(result); String S = "" ; if (result) { S = m.group(); System.out.println(S); } return S; } //S1要查找的正則表達式,S2查找源 public boolean regex1(String S1,String S2){ Pattern p = Pattern.compile(S1); Matcher m = p.matcher(S2); boolean result = m.find(); System.out.println(result); return result; } } |
希望本文所述對大家的java程序設計有所幫助。