2014-12-03 5 views
1

폴더의 파일을 읽고 이름을 바꿔야합니다. 이 경우 이름에 앵무새가있는 파일이 3 개, 조커가 4 개, 버즈가 4 개가 있습니다.Java - 파일 이름 수 및 이름 바꾸기

하위 문자열을 사용하여 버즈, 앵무새 및 버즈 단어를 얻을 수 있습니다. 그러나 나는 그들을 통해 가야하고 얼마나 많은 시간이 각각 발생하는지 계산하고 01,02,03으로 이름을 지어야합니다. 일단 그룹화되면. 나는 힘든 시간을 보내고있다. 어떤 제안이 도움이됩니다.

원본 파일 이름

apple_orange_buzz_banana01.txt
apple_orange_buzz_banana02.txt
apple_orange_buzz_banana05.txt
apple_orange_buzz_banana06.txt
apple_orange_joker_banana03.txt
apple_orange_joker_banana04.txt
apple_orange_joker_banana07.txt
apple_orange_joker_banana10.txt
apple_orange_parrot_banana08.txt
apple_orange_parrot_banana09.txt
apple_orange_parrot_banana11.txt

바꾸기 파일명


buzz04.txt
buzz03.txt
buzz02.txt joker01.txt
buzz01.txt joker02.txt
joker03.txt
joker04.txt

parrot01.txt
parrot02.txt
parrot03.txt

감사합니다

+1

처럼 보일 수 있습니까? 입력으로 버즈, 조커, 버즈, 앵무새 등을 사용할 수 있습니까? –

+0

연속되지 않습니다.나는 방금 그것을 읽도록 명확하게하기 위해 그것을 그렇게 주문했다. 해당 폴더에는 약 50-80 개의 파일이 있습니다. –

+0

정규 표현식 사용 –

답변

1

당신은 파일의 각 종류의 카운터 저장하기 위해지도를 사용할 수 있습니다 (버즈, 조커, ...) 정규식은 관심있는 이름의 일부를 찾을 수 있습니다.

그래서 코드는`buzz`es,`joker`s와`parrot`s 연속 있습니까

Pattern p = Pattern.compile("apple_orange_(\\w+)_banana\\d+[.]txt"); 
Map<String, Integer> map = new HashMap<>(); 

File dir = new File("d:/zzz");//path to directory containing your files 
File[] files = dir.listFiles();//you can provide file filter here 
Arrays.sort(files);//lets make sure that files are sort alphabetically 

for (File f : files) { 
    Matcher m = p.matcher(f.getName()); 
    if (m.find()) { 
     String name = m.group(1); 
     int counter = map.getOrDefault(name, 0) + 1; 
     map.put(name, counter); 
     f.renameTo(new File(dir, String.format("%s%02d.txt", name, counter))); 
    } 
} 
0

그냥 알파벳 순으로 파일을 정렬 한 후 배열에 파일 이름을 분할하고 이름을 변경 :

//get list of files 
String path = "C:/Users/your/folder/"; 
File folder = new File(path); 
File[] listOfFiles = folder.listFiles(); 

//this will sort alphabetically 
java.util.Collections.sort(listOfFiles); 

String mainPart = ""; 
int counter = 1; 

for (File file : listOfFiles) { 
    if (file.isFile()) { 
     //get parts 
     String[] parts = file.getName()).split("_"); 

     //note: make sure file name has consistent formatting 
     if(!mainPart.equals(parts[2])){ 
      mainPart = parts[2]; 
      counter = 1; 
     } 

     //keep track if the number needs a leading zero. 
     String zero = "" 
     if(counter < 10) 
      zero = "0"; 

     //note: check to see if renameTo was successful 
     file.renameTo(new File(path + mainPart + zero + counter + ".txt")); 
     counter++;  
    } 
} 

이 코드를 테스트하지 않았으므로 사소한 구문 오류가있을 수 있습니다. 그러나 당신은 아이디어를 얻습니다.

+0

내 눈을 멀게하고 파일 이름을 '01' 또는'02'로 바꿉니 까? 난 당신이 카운터에 대한'DecimalFormat' 개체가 필요하다고 생각합니다. –

+0

@DrewKennedy 숫자 1-9에 0을 추가하도록 업데이트되었습니다. –

+1

너희들 모두 최고야. 매우 다양한 아이디어. 나는 그것에 대해 노력하고 그것이 어떻게되는지 보게 될 것입니다. –

0

나는 새로운 파일 접두사를 키로 사용하고 값의 이름을 바꿀 파일 목록을 사용하여 Map을 만드는 방법에 접근하고 싶습니다. 그런 다음 루프를 사용하여 이름을 바꿉니다.

파일 목록이 올하지만이의 요점을 얻을 수있는 곳에서 확실하지 :

List<File> files = new ArrayList<File>(); 

files.add(new File("apple_orange_buzz_banana01.txt")); 
files.add(new File("apple_orange_buzz_banana02.txt")); 
files.add(new File("apple_orange_buzz_banana05.txt")); 
files.add(new File("apple_orange_buzz_banana06.txt")); 


files.add(new File("apple_orange_joker_banana03.txt")); 
files.add(new File("apple_orange_joker_banana04.txt")); 
files.add(new File("apple_orange_joker_banana07.txt")); 
files.add(new File("apple_orange_joker_banana10.txt")); 

files.add(new File("apple_orange_parrot_banana08.txt")); 
files.add(new File("apple_orange_parrot_banana09.txt")); 
files.add(new File("apple_orange_parrot_banana11.txt")); 


Map<String,List<File>> prefixMap = new HashMap<String,List<File>>(); 

for (File f : files) { 
    String[] splits = f.getName().split("_"); 

    if (splits.length == 4) { 
     String prefix = splits[2]; 
     if (!prefixMap.containsKey(prefix)) { 
      prefixMap.put(prefix, new ArrayList<File>()); 
     } 
     prefixMap.get(prefix).add(f); 
    } 
} 

// Now rename them 
for (String p : prefixMap.keySet()) { 
    int counter = 1; 

    for (File f : prefixMap.get(p)) { 
     f.renameTo(new File(p+String.format("%02d", counter)+".txt")); 
     counter++; 
    } 
}