반응형
Java의 패턴과 일치하는 디렉토리의 파일 나열
이 질문에 이미 답변이 있습니다.
주어진 디렉토리에서 패턴 (pref regex)과 일치하는 파일 목록을 얻는 방법을 찾고 있습니다.
다음 코드와 함께 apache의 commons-io 패키지를 사용하는 온라인 자습서를 찾았습니다.
Collection getAllFilesThatMatchFilenameExtension(String directoryName, String extension)
{
File directory = new File(directoryName);
return FileUtils.listFiles(directory, new WildcardFileFilter(extension), null);
}
그러나 그것은 단지 기본 컬렉션을 반환합니다 ( 문서 에 따르면 그것은 컬렉션입니다 java.io.File
). 유형 안전 제네릭 컬렉션을 반환하는 방법이 있습니까?
File # listFiles (FilenameFilter)를 참조하십시오 .
File dir = new File(".");
File [] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
});
for (File xmlfile : files) {
System.out.println(xmlfile);
}
Java 8부터 람다를 사용하고 더 짧은 코드를 얻을 수 있습니다.
File dir = new File(xmlFilesDirectory);
File[] files = dir.listFiles((d, name) -> name.endsWith(".xml"));
Java 7 이후로 java.nio 패키지를 사용하여 동일한 결과를 얻을 수 있습니다.
Path dir = ...;
List<File> files = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{java,class,jar}")) {
for (Path entry: stream) {
files.add(entry.toFile());
}
return files;
} catch (IOException x) {
throw new RuntimeException(String.format("error reading folder %s: %s",
dir,
x.getMessage()),
x);
}
다음 코드는의 accept 메서드를 기반으로 파일 목록을 만듭니다 FileNameFilter
.
List<File> list = Arrays.asList(dir.listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".exe"); // or something else
}}));
기존 코드를 둘러싼 래퍼는 어떻습니까?
public Collection<File> getMatchingFiles( String directory, String extension ) {
return new ArrayList<File>()(
getAllFilesThatMatchFilenameExtension( directory, extension ) );
}
그래도 경고를 던질 것입니다. 당신이 그 경고와 함께 살 수 있다면, 당신은 끝난 것입니다.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class CharCountFromAllFilesInFolder {
public static void main(String[] args)throws IOException {
try{
//C:\Users\MD\Desktop\Test1
System.out.println("Enter Your FilePath:");
Scanner sc = new Scanner(System.in);
Map<Character,Integer> hm = new TreeMap<Character, Integer>();
String s1 = sc.nextLine();
File file = new File(s1);
File[] filearr = file.listFiles();
for (File file2 : filearr) {
System.out.println(file2.getName());
FileReader fr = new FileReader(file2);
BufferedReader br = new BufferedReader(fr);
String s2 = br.readLine();
for (int i = 0; i < s2.length(); i++) {
if(!hm.containsKey(s2.charAt(i))){
hm.put(s2.charAt(i), 1);
}//if
else{
hm.put(s2.charAt(i), hm.get(s2.charAt(i))+1);
}//else
}//for2
System.out.println("The Char Count: "+hm);
}//for1
}//try
catch(Exception e){
System.out.println("Please Give Correct File Path:");
}//catch
}
}
참고 URL : https://stackoverflow.com/questions/2102952/listing-files-in-a-directory-matching-a-pattern-in-java
반응형
'Nice programing' 카테고리의 다른 글
python SimpleHTTPServer를 localhost에서만 실행할 수 있습니까? (0) | 2020.10.13 |
---|---|
'android-24'를 컴파일하려면 JDK 1.8 이상이 필요합니다. (0) | 2020.10.13 |
Symfony2-자체 공급 업체 번들 생성-프로젝트 및 Git 전략 (0) | 2020.10.13 |
Rails에서 캐스케이드 삭제를 설정할 수 있습니까? (0) | 2020.10.13 |
Rails Routes 네임 스페이스 및 form_for (0) | 2020.10.13 |