파일구조 / 디렉토리 구조 / 탐색기 / JAVA

2016. 1. 5. 11:17language/java

JAVA로 개발되어 있다. 

 

특정 루트의 폴더 구조를

 

계단식 목록으로

 

TXT 파일로 생성하는 소스이다.

 


 

txt파일의 내용을 엑셀로 복사해서 써도되는데

 

이는 간격이 Tab로 구현되어있기 때문에

 

각 칸에 알맞게 들어간다.

 

 

FileDirAna.java

package fileDirAnalysis;
 
import java.io.IOException;
 
public class FileDirAna {
 // 저장할 txt 파일
 static String SAVE_TXT_FILE = "D:\\a.txt";
 
// static String SEARCH_FULL_DIR = "D:\\project\\test";
 static String SEARCH_FULL_DIR = "D:\\project\\test";
 static String LAST_DIR = "\\test";
 
 public static void main(String[] args) throws IOException {
  
//  new FileDirAnalysis(SAVE_TXT_FILE, SEARCH_FULL_DIR, LAST_DIR);
  new FileDirAnalysis(SAVE_TXT_FILE, SEARCH_FULL_DIR, LAST_DIR, true);
  
   } 
}
 
cs

 

 

FileDirAnalysis.java

package fileDirAnalysis;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
public class FileDirAnalysis {
 // 구조를 조사할 디렉토리
 private String lastDir = "";
 
 private String filePath = "";
 int fileCnt = 0;
 int dirCnt = 0;
 
 private FileWriter out = null;
 private String dirTab;
 private String fileTab;
 
 // ///////////////////////////////////
 // 파일 읽기
 BufferedReader br = null;
 InputStreamReader isr = null;
 FileInputStream fis = null;
 
 String titleTag = "<title>";
 
 String tempStr = "";
 String content = "";
 
 // xml 파싱
 String titleTagText = "title";
 
 DocumentBuilderFactory dbf = null;
 DocumentBuilder dbuilder = null;
 Document doc = null;
 NodeList nodeList = null;
 InputSource isource = new InputSource();
 Element element = null;
 
 // ///////////////////////////////////
 
 /**
  * 폴더구조 생성
  * 
  * @param saveTxtFile
  *            저장할 파일 (ex : D:\\a.txt)
  * @param searchFullDir
  *            조회할 dir (ex : D:\\temp\\01\\aaa)
  * @param lastDir
  *            조회할 dir (ex : \\aaa)
  * @throws IOException
  */
 public FileDirAnalysis(String saveTxtFile, String searchFullDir,
   String lastDir) throws IOException {
  out = new FileWriter(saveTxtFile);
  this.lastDir = lastDir;
  if (fileCnt == 0) {
   System.out.println("start ====================");
   out.write("start ====================\r\n");
  }
  
  fileDirAna(searchFullDir);
  
  System.out.println("결과 ====================");
  System.out.println("파일개수 : " + fileCnt);
  System.out.println("폴더개수 : " + dirCnt);
  System.out.println("합계 : " + (fileCnt + dirCnt));
  System.out.println("end ====================");
  out.write("결과 ====================\r\n");
  out.write("파일개수 : " + fileCnt + "\r\n");
  out.write("폴더개수 : " + dirCnt + "\r\n");
  out.write("합계 : " + (fileCnt + dirCnt) + "\r\n");
  out.write("end ====================\r\n");
  out.close();
 }
 
 /**
  * 폴더구조 생성 / jsp파일은 title 포함
  * 
  * @param saveTxtFile
  *            저장할 파일 (ex : D:\\a.txt)
  * @param searchFullDir
  *            조회할 dir (ex : D:\\temp\\01\\aaa)
  * @param lastDir
  *            조회할 dir (ex : \\aaa)
  * @param readJsp
  *            (true : jsp title 추출)
  * @throws IOException
  */
 public FileDirAnalysis(String saveTxtFile, String searchFullDir,
   String lastDir, boolean readJsp) throws IOException {
  out = new FileWriter(saveTxtFile);
  this.lastDir = lastDir;
  if (fileCnt == 0) {
   System.out.println("start ====================");
   out.write("start ====================\r\n");
  }
 
  fileDirAnaAndJspTitle(searchFullDir, readJsp);
 
  System.out.println("결과 ====================");
  System.out.println("파일개수 : " + fileCnt);
  System.out.println("폴더개수 : " + dirCnt);
  System.out.println("합계 : " + (fileCnt + dirCnt));
  System.out.println("end ====================");
  out.write("결과 ====================\r\n");
  out.write("파일개수 : " + fileCnt + "\r\n");
  out.write("폴더개수 : " + dirCnt + "\r\n");
  out.write("합계 : " + (fileCnt + dirCnt) + "\r\n");
  out.write("end ====================\r\n");
  out.close();
 }
 
 
 
 
 
 
 
 
 
 
 /**
  * 
  * @param searchRoot
  * @param readJsp
  * @throws IOException
  */
 public void fileDirAna(String searchRoot)
   throws IOException {
  File dir = new File(searchRoot);
  File[] fileList = dir.listFiles();
 
  fileList = fileSort(dir);
 
  for (int i = 0; i < fileList.length; i++) {
   File file = fileList[i];
 
   if (file.isFile()) {
    fileCnt++;
    filePath = file.getCanonicalPath().toString();
 
    filePath = filePath.substring(filePath.indexOf(lastDir));
    fileTab = "";
 
    // 뎁스 구하기
    for (int j = 0; j < filePath.length(); j++) {
     if (filePath.charAt(j) == '\\') {
      fileTab += "\t";
     }
    }
    
    out.write(fileTab + file.getName() + "\r\n");
 
   } else if (file.isDirectory()) {
    dirCnt++;
    filePath = file.getCanonicalPath().toString();
 
    filePath = filePath.substring(filePath.indexOf(lastDir));
    dirTab = "";
 
    // 뎁스 구하기
    for (int j = 0; j < filePath.length(); j++) {
     if (filePath.charAt(j) == '\\') {
      dirTab += "\t";
     }
    }
 
    out.write(dirTab + file.getName() + "\r\n");
    // 재귀
    fileDirAna(file.getCanonicalPath().toString());
   }
  }
 }
 
 /**
  * 
  * @param searchRoot
  * @param readJsp
  * @throws IOException
  */
 public void fileDirAnaAndJspTitle(String searchRoot, boolean readJsp)
   throws IOException {
  File dir = new File(searchRoot);
  File[] fileList = dir.listFiles();
  
  fileList = fileSort(dir);
  
  for (int i = 0; i < fileList.length; i++) {
   File file = fileList[i];
   
   if (file.isFile()) {
    fileCnt++;
    filePath = file.getCanonicalPath().toString();
    
    filePath = filePath.substring(filePath.indexOf(lastDir));
    fileTab = "";
    
    // 뎁스 구하기
    for (int j = 0; j < filePath.length(); j++) {
     if (filePath.charAt(j) == '\\') {
      fileTab += "\t";
     }
    }
    
    // jsp 파일에서 title 읽기
    if(readJsp){
     // 확장자
     String fileExt = file.getName().substring(file.getName().lastIndexOf(".")+1, file.getName().length());
     String titleText = "";
     if(fileExt.toLowerCase().equals("jsp")){
      titleText = getTextOfJspFile(file.getCanonicalPath().toString());
     }
     
     out.write(fileTab + file.getName() + "\t" + titleText + "\r\n");
    }else{
     out.write(fileTab + file.getName() + "\r\n");
    }
    
   } else if (file.isDirectory()) {
    dirCnt++;
    filePath = file.getCanonicalPath().toString();
    
    filePath = filePath.substring(filePath.indexOf(lastDir));
    dirTab = "";
    
    // 뎁스 구하기
    for (int j = 0; j < filePath.length(); j++) {
     if (filePath.charAt(j) == '\\') {
      dirTab += "\t";
     }
    }
    
    out.write(dirTab + file.getName() + "\r\n");
    // 재귀
    fileDirAnaAndJspTitle(file.getCanonicalPath().toString(), readJsp);
   }
  }
 }
 
 /**
  * 파일 정렬 - 폴더, 파일 순
  * 
  * 
  * @param fileList
  * @return
  */
 public File[] fileSort(File dir) {
  File[] fileList = dir.listFiles();
  File[] fileList1 = dir.listFiles();
 
  int fileListCnt = 0;
  for (int i = 0; i < fileList1.length; i++) {
   if (fileList1[i].isDirectory()) {
    fileList[fileListCnt] = fileList1[i];
    fileListCnt++;
   }
  }
 
  for (int i = 0; i < fileList1.length; i++) {
   if (fileList1[i].isFile()) {
    fileList[fileListCnt] = fileList1[i];
    fileListCnt++;
   }
  }
 
  return fileList;
 }
 
 /**
  * jsp 파일에서 title 속성 읽기
  * 
  * @param jspFilePath
  * @return
  */
 public String getTextOfJspFile(String jspFilePath) {
  String str = "";
  File file = new File(jspFilePath);
 
  try {
   fis = new FileInputStream(file);
 
   isr = new InputStreamReader(fis, "UTF-8");
   br = new BufferedReader(isr);
 
   // title 태그 추출
   while ((tempStr = br.readLine()) != null) {
    content = tempStr;
    if (content.indexOf(titleTag) != -1) {
     str = content.substring(content.indexOf(titleTag));
    }
   }
 
   // title 태그에서 text 추출
   if (!str.equals("")) {
    dbf = DocumentBuilderFactory.newInstance();
    dbuilder = dbf.newDocumentBuilder();
    isource.setCharacterStream(new StringReader(str));
    doc = dbuilder.parse(isource);
    nodeList = doc.getElementsByTagName(titleTagText);
   
    element = (Element) nodeList.item(0);
    str = element.getTextContent();
   }
 
  } catch (SAXException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ParserConfigurationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   try {
    if (fis != null)
     fis.close();
    if (isr != null)
     isr.close();
    if (br != null)
     br.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
 
  }
 
  return str;
 }
}
 
 
cs

 

 

도움이 되셨다면 공감을 부탁드립니다. ^^