반응형
Java의 패턴과 일치하는 디렉토리에 파일 나열
특정 디렉토리의 패턴(프리프 정규식)과 일치하는 파일 목록을 가져오는 방법을 찾고 있습니다.
다음 코드와 함께 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에서는 lamda를 사용하여 보다 짧은 코드를 얻을 수 있습니다.
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);
}
다음 코드에 따라 파일 목록이 작성됩니다.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
반응형
'programing' 카테고리의 다른 글
Python으로 HTML 이메일 보내기 (0) | 2022.11.07 |
---|---|
정수에서 자릿수 길이를 찾으려면 어떻게 해야 합니까? (0) | 2022.11.07 |
페이지 새로고침 시 Nuxtjs, VUEX 및 Firebase 인증 (0) | 2022.11.07 |
PHP mysql 삽입 날짜 형식 (0) | 2022.11.07 |
저는 json 데이터를 가진 authorsjson이라는 JSON 컬럼을 가지고 있습니다.이름이 지정된 문자열로 시작하는 모든 사용자를 찾습니다. (0) | 2022.11.07 |