시소당
- Finder.java
/*
* @Finder.java Created on 2006. 08. 24
*
* Copyright (c) 2005 GHLab.com All rights reserved.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
/**
* 파일 총 라인수 구하기.
*
* @version 1.0
* @author 김건호
*/
class Finder {
public static long totalFileSize = 0; // 전체 파일 사이즈 저장
public long fileSize = 0; // 파일 사이즈 저장
public static int totalFileLineCount = 0;
public int fileLineCount = 0;
// 파일 정보 저장
public ArrayList<FileDTO> fileList = new ArrayList<FileDTO>();
public final static int TOTAL_FIND_CODE = 0; // 전체 검색 코드
public final static int FILENAME_FIND_CODE = 1; // 파일명 검색 코드
public final static int EXTENSION_FIND_CODE = 2; // 확장자 검색 코드
public int findTypeCode = TOTAL_FIND_CODE; // 검색 코드
// 검색 파일명
public String findFileName = "*.*";
// 하위디렉토리 검색 여부
public boolean isFindUnderDir = false;
// 대소문자 구분
public boolean isUpperLower = false;
public static void main(String[] args) {
if (args.length == 0 || args.length > 3) {
StringBuffer sb = new StringBuffer();
sb
.append("사용법을 갈켜드리겠습니다~\n")
.append(
"예) Windows 폴더 내의 모든 파일의 용량 및 라인수를 추출하고 싶다면 아래처럼~\n\n")
.append("java Finder c:\\windows\n\n")
.append("파일을 지정하고 싶다면(기본 전체 파일 검색) 아래와 같은 옵션을 붙이면 됩니다.\n")
.append("확장자 지정 검색 -e, 파일 지정 검색 : -f\n")
.append("예) Windows 폴더 내의 확장자가 exe 인 파일을 검색\n\n")
.append("java Finder c:\\windows -e exe\n\n")
.append("하위 폴더를 포함하여 검색하고 싶다면 s 옵션을 붙이면 됩니다.\n")
.append(
"예) Windows 폴더와 하위 폴더의 모든 파일 중 파일명이 notepad.exe인 파일을 검색\n\n")
.append("java Finder c:\\windows -sf notepad.exe\n\n")
.append("파일명을 대소문자 구분하여 검색하려면 u 옵션을 붙이면 됩니다.\n")
.append(
"예) Windows 폴더와 하위 폴더의 모든 파일 중 확장자가 exe인 파일을 검색\n\n")
.append("java Finder c:\\windows -sue exe");
System.out.println(sb.toString());
System.exit(1);
}
Finder f = new Finder();
// 검색 경로
String path = null;
// 옵션
String option = "";
if (args.length > 0)
path = args[0]; // 검색 경로 저장
// 인자 갯수에 따른 분류
if (args.length > 1) {
// 옵션 저장
option = args[1];
// 검색 파일명 또는 확장자 저장
f.findFileName = args[2];
}
// 옵션에 의한 데이터 셋팅
if (option.indexOf("s") != -1)
f.isFindUnderDir = true;
// 대소문자 구분하지 않을 경우
if (option.indexOf("u") != -1)
f.isUpperLower = true;
// 확장자 검색일 경우
if (option.indexOf("e") != -1)
f.findTypeCode = Finder.EXTENSION_FIND_CODE;
// 파일명 검색일 경우
if (option.indexOf("f") != -1)
f.findTypeCode = Finder.FILENAME_FIND_CODE;
// 확장자 검색과 파일명 검색은 함께 쓸수 없다.
if (option.indexOf("e") != -1 && option.indexOf("f") != -1)
System.out
.println("확장자 검색과 파일명 검색 옵션 모두 입력하셨습니다.\n파일명 검색 모드로 자동 설정됩니다.");
// 디렉토리 존재 여부
File file = new File(path);
if (file.isDirectory() == false) {
System.out.println("정확한 경로를 입력하여 주십시오.");
System.exit(1);
}
// 디렉토리 끝에 \ 또는 / 이 없으면 붙임
String lastChar = path.substring(path.length() - 1, path.length());
if (lastChar.equals(File.separator) == false) {
path = path + File.separator;
}
try {
f.getSize(path);
} catch (Exception e) {
System.out.println("에러!! : " + e.getMessage());
e.printStackTrace();
}
System.out.println("검색된 파일 갯수 : " + f.fileList.size());
// 검색된 파일 갯수가 있을 경우에 정보 출력
if (f.fileList.size() > 0) {
System.out.println("총 파일 사이즈 : " + byteTranslater(totalFileSize));
System.out.println("총 라인수 : " + totalFileLineCount + "라인");
System.out.print("검색된 파일 정보를 보시겠습니까?(Y/N) : ");
String choice = null;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
choice = in.readLine();
} catch (Exception e) {
choice = "N";
}
choice = choice.toUpperCase();
if (choice.equals("Y")) {
// 파일 정보 추출
FileDTO[] fdto = f.getFileList();
for (int i = 0; i < fdto.length; i++) {
System.out.println("파일 : " + fdto[i].getFilePath()
+ fdto[i].getFileName() + ", 사이즈 : "
+ byteTranslater(fdto[i].getFileSize())
+ ", 라인수 : " + fdto[i].getFileLineCount());
}
}
}
System.exit(1);
}
/**
* 해당 경로에서 파일을 찾아 용량, 라인수를 측정
*
* @param path
* 파일을 찾을 경로
* @param findFileName
* 모든 파일 찾기(*.*), 확장자로 찾기(*.java), 파일명 찾기(test.java)
* @param isFindUnderDir
* 하위디렉토리 검색 여부
* @throws Exception
*/
public void getSize(String path) throws Exception {
File dir = new File(path);
String[] list = dir.list();
File file;
BufferedReader br = null;
String fileName = null; // 파일명 저장
String filePath = null; // 파일 경로
String findFileName = this.findFileName;
for (int i = 0; i < list.length; i++) {
file = new File(path + list[i]);
fileSize = 0; // 해당 파일 크기 0으로 초기화
fileLineCount = 0; // 해당 파일 총 라인수 0으로 초기화
// 파일만 계산
if (file.isFile()) {
fileName = file.getName(); // 파일명 추출
// 대소문자 구분 하지 않는다면 모두 대문자로 변경
if (this.isUpperLower == false) {
fileName = fileName.toUpperCase(Locale.KOREAN);
findFileName = findFileName.toUpperCase(Locale.KOREAN);
}
filePath = file.getPath(); // 파일경로 추출
// 검색 형태에 따른 조건 설정
if ((findTypeCode == TOTAL_FIND_CODE)
|| (findTypeCode == EXTENSION_FIND_CODE && fileName
.substring(fileName.lastIndexOf(".") + 1,
fileName.length()).equals(findFileName))
|| (findTypeCode == FILENAME_FIND_CODE && fileName
.equals(findFileName))) {
br = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath)));
// 라인수 추출
while (br.readLine() != null) {
fileLineCount++;
}
fileSize = file.length(); // 파일 크기 추출
FileDTO fdto = new FileDTO();
fdto.setFileSize(fileSize);
fdto.setFileName(file.getName());
fdto.setFilePath(filePath.substring(0, filePath
.lastIndexOf(File.separator) + 1));
fdto.setFileLineCount(fileLineCount);
fileList.add(fdto);
}
}
// 해당 폴더내의 모든 파일의 크기 추출을 위한 연산
totalFileSize += fileSize;
// 해당 폴더내의 모든 파일의 라인수 추출을 위한 연산
totalFileLineCount += fileLineCount;
// 하위 디렉토리가 있고, 옵션을 하위 디렉토리 검색을 지정했을 경우 재귀호출
if (file.isDirectory() && isFindUnderDir)
getSize(file.getPath() + File.separator);
}
}
/**
* ArrayList 에 담겨진 파일 정보 DTO를 배열로 전환하여 받아옴
*
* @return 파일 정보 목록
*/
public FileDTO[] getFileList() {
FileDTO[] result = new FileDTO[fileList.size()];
for (int i = 0; i < result.length; i++) {
result[i] = new FileDTO();
result[i] = fileList.get(i);
}
return result;
}
/**
* 파일 사이즈 단위 변환
*
* @param size
* long 형 타입의 파일 사이즈
* @return KB, MB, GB 로 변환한 사이즈
*/
public static String byteTranslater(long size) {
NumberFormat nf = NumberFormat.getIntegerInstance();
java.text.DecimalFormat df = new java.text.DecimalFormat("#,##0.00");
int intSize = 0;
int kbyteSize = 1024;
double doubleSize = 0;
String returnSize = null;
// 파일 사이즈가 1000, 2000 형식이므로 기가는 1024 가 아닌 1000을 기준으로.
if (size >= (1000 * 1024 * 1024)) {
intSize = new Long(size / (1000 * 1024 * 1024)).intValue();
return nf.format(intSize) + "GB";
} else if (size > (kbyteSize * 1024)) {
intSize = (int) (((double) size) / ((double) (kbyteSize * 1024)) * 100);
doubleSize = (double) (((double) intSize) / 100);
returnSize = df.format(doubleSize);
if (returnSize.lastIndexOf(".") != -1) {
if ("00".equals(returnSize.substring(returnSize.length() - 2,
returnSize.length()))) {
returnSize = returnSize.substring(0, returnSize
.lastIndexOf("."));
}
}
return returnSize + "MB";
} else if (size > kbyteSize) {
intSize = new Long(size / kbyteSize).intValue();
return nf.format(intSize) + "KB";
} else {
// return nf.format(size) + "Byte";
return "1KB";
}
}
}
/**
* 파일 정보 저장 객체
*
* @version 1.0
* @author 김건호
*/
class FileDTO {
public int fileLineCount;
private long fileSize;
private String filePath;
private String fileName;
public FileDTO() {
fileSize = 0;
filePath = null;
}
/**
* @return the fileLineCount
*/
public int getFileLineCount() {
return fileLineCount;
}
/**
* @param fileLineCount
* the fileLineCount to set
*/
public void setFileLineCount(int fileLineCount) {
this.fileLineCount = fileLineCount;
}
/**
* @return the fileName
*/
public String getFileName() {
return fileName;
}
/**
* @param fileName
* the fileName to set
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* @return the filePath
*/
public String getFilePath() {
return filePath;
}
/**
* @param filePath
* the filePath to set
*/
public void setFilePath(String filePath) {
this.filePath = filePath;
}
/**
* @return the fileSize
*/
public long getFileSize() {
return fileSize;
}
/**
* @param fileSize
* the fileSize to set
*/
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
}