728x90
- Java로 파일탐색기를 만들어보자
간단하게 만들어볼 게 뭐가 있을까 고민하다가 '파일탐색기'를 만들어봐야겠다 생각했다.
(Composite 패턴 공부하면서 재귀함수를 활용하면 금방 만들겠다 생각이 들었음)
[GoF] Composite 패턴 : 그릇과 내용물을 동일시한다 [재귀적인 구조를 만드는 패턴]
- Composite 패턴 : 그릇과 내용물을 동일시한다 Composite 패턴은 컴퓨터 파일 시스템의 '디렉터리(Directory)'처럼 '중첩'된 구조, 재귀적인 구조를 만들어내는 패턴이다. 그릇과 내용물을 동일하게 만
yermi.tistory.com
main에서 실행될 findFile이라는 메서드이다.
파일개수를 세줄 count라는 변수는 전역으로 선언하였고, Scanner의 nextLine도 입맛에 맞게 수정하였다.
static Scanner sc = new Scanner(System.in);
static long count = 0;
private void findFile() {
String drive = nextLine("탐색할 드라이브를 입력해주세요. > ");
String keyword = nextLine("검색할 파일명을 입력해주세요. > ");
String condition = nextLine("정확히 일치하는 파일만 찾겠습니까? [Y/N] > ");
boolean flag = "Y".equals(condition.toUpperCase());
if(!checkedDriveReg(drive)) {
System.err.println("드라이브를 확인해주세요. > " + drive);
} else if(keyword.isEmpty()) {
System.err.println("검색할 파일명을 입력해주세요.");
} else {
scanDir(drive.toUpperCase() + ":\\", keyword, flag);
System.out.printf("총 %d개의 파일을 찾았습니다.", count);
}
}
private String nextLine(String str) {
System.out.print(str);
return sc.nextLine();
}
드라이브는 알파벳만 들어가야 하기에 정규표현식으로 예외처리 하였다.
private boolean checkedDriveReg(String driveName) {
return driveName.matches("^[a-zA-Z]");
}
디렉토리를 스캔할 scanDir이라는 메서드를 만들어주고, 해당 메서드를 재귀적으로 호출하였다.
condition이란 변수를 활용하여 keyword와 전체가 일치할지, 부분적으로 일치할지 구분지었다.
private void scanDir(String path, String keyword, boolean condition) {
File file = new File(path);
if(file.isDirectory() && !file.getName().equals("System Volume Information")) {
File[] files = file.listFiles();
if(files != null) {
for(File f : files) {
if(condition) {
if(f.getName().equals(keyword)) {
System.out.println(f.getAbsolutePath());
count++;
}
} else {
if(f.getName().contains(keyword)) {
System.out.println(f.getAbsolutePath());
count++;
}
}
if(f.isDirectory()) {
scanDir(f.getAbsolutePath(), keyword, condition);
}
}
}
}
}
만들고 나니 '정확히 일치하는 파일만 찾겠다'고 할 때 확장자도 입력해줘야 탐색이 되었다.
확장자 제거하고 비교하는 로직을 만들어야 할 듯 한데 이건 다음에..ㅎ
- FileFinder.java
package toy;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileFinder {
static Scanner sc = new Scanner(System.in);
static long count = 0;
public static void main(String[] args) throws IOException {
FileFinder fileFinder = new FileFinder();
fileFinder.findFile();
}
private void findFile() {
String drive = nextLine("탐색할 드라이브를 입력해주세요. > ");
String keyword = nextLine("검색할 파일명을 입력해주세요. > ");
String condition = nextLine("정확히 일치하는 파일만 찾겠습니까? [Y/N] > ");
boolean flag = "Y".equals(condition.toUpperCase());
if(!checkedDriveReg(drive)) {
System.err.println("드라이브를 확인해주세요. > " + drive);
} else if(keyword.isEmpty()) {
System.err.println("검색할 파일명을 입력해주세요.");
} else {
scanDir(drive.toUpperCase() + ":\\", keyword, flag);
System.out.printf("총 %d개의 파일을 찾았습니다.", count);
}
}
private void scanDir(String path, String keyword, boolean condition) {
File file = new File(path);
if(file.isDirectory() && !file.getName().equals("System Volume Information")) {
File[] files = file.listFiles();
if(files != null) {
for(File f : files) {
if(condition) {
if(f.getName().equals(keyword)) {
System.out.println(f.getAbsolutePath());
count++;
}
} else {
if(f.getName().contains(keyword)) {
System.out.println(f.getAbsolutePath());
count++;
}
}
if(f.isDirectory()) {
scanDir(f.getAbsolutePath(), keyword, condition);
}
}
}
}
}
private boolean checkedDriveReg(String driveName) {
return driveName.matches("^[a-zA-Z]");
}
private String nextLine(String str) {
System.out.print(str);
return sc.nextLine();
}
}
GitHub - algo-gaja/toy-project: 간단하게 만들어보는 Toy Project🧩
간단하게 만들어보는 Toy Project🧩. Contribute to algo-gaja/toy-project development by creating an account on GitHub.
github.com
728x90