본문 바로가기

IT/Java

[API] FileUtils

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

프로그래밍을 하다보면 Java API를 이용하여 파일들을 handle할 일이 생기지만

항상 검색을 하면서 그 순간에만 이해를 하고 다시 까먹게 된다. 

이번 글을 통해 완벽히 File handle 관련 Java API를 이해할 것이다.

 

1.directory 파일 전체 출력

 - 아래의 소스는 directory안에 파일(txt등)만 존재할 경우를 가정하여 작성되었다.

   만약 directory 안에 directory가 존재하고 그 안에도 파일이 존재할 경우 안에 있는 directory명까지 출력된다.

   이를 해결하기 위해서는 아래 2번을 확인하면 된다.

public void getFileLists(String dirRoot){
	File dir = new File(dirRoot);
	if(dir.isDirectory()){		//파일이 디렉토리일 경우
		for(File file : dir.listFiles()){	// 디렉토리 내 파일들을 하나 씩 읽어와서
			System.out.println(file.getName());	// 파일 이름 출력
		}
	}
}

 

2.directory 속 directory 구조에서 파일만 전체 출력

 - 이를 위해서는 재귀함수 호출 구조가 필요하다. 그 이유는 하나의 directory안에서 수행할 작업은

   파일일 경우만 출력을 하고 directory가 존재한다면 그 directory를 기준으로 또 파일일 경우에만 출력하는

   동일한 작업을 하기 때문이다. 만약 directory안에 1개의 directory만 존재한다는 가정이라면 재귀함수가 필요없을 수

   있으나 directory의 개수를 모르기 때문에 재귀함수가 꼭 필요하다.

public void getFileListsOnSubDirectory(String dirRoot){
	File dir = new File(dirRoot);
	if(dir.isDirectory()){
		for(File file : dir.listFiles()){
			System.out.println(file.getName());	//파일일 경우 출력
			if(file.isDirectory()){				//directory일 경우
				getFileListsOnSubDirectory(file.getAbsolutePath());	// 재귀함수 호출
			}
		}
	}
}

 

3.file 확장자 구분하여 출력

 - 원하는 확장자를 아래 소스의 'txt'를 바꿔주면 된다.

public void getTxtFileLists(String dirRoot){
	File dir = new File(dirRoot);
	String tempFileName;
	if(dir.exists() && dir.isDirectory()){		//존재하면서 디렉토리일 경우
		for(File file : dir.listFiles()){
			tempFileName = file.getName();
			int fileLength = tempFileName.length();
			if(tempFileName.substring(fileLength-3).equals("txt")){
				System.out.println(tempFileName);
			}
		}
	}
}

 

4.file 한줄 읽기

 - file 읽기에 가장 쉬운 방법인 BufferedReader이다.

   BufferedReader는 FileReader클래스를 생성자로 받으며 FileReader는 File 클래스를 생성자로 받는다.

   File Class는 실제 File을 자바 메모리(JVM)에 올린다고 볼 수 있으며, FileReader로 file을 읽을 준비, 

   BufferedReader로 실제 한줄로 읽는 것이다. 각자 Reader가 제공하는 API가 다르기 때문에 한 번 소스를 분석하면

   되지만 이해를 쉽게하기 위해 Reader의 역할을 위처럼 설명했다.

public void getLineFromFile(String dirRoot){
	File file = new File(dirRoot+"\\sample1.txt");
	try {
		BufferedReader br = new BufferedReader(new FileReader(file));
		String readLine = "";
		while((readLine=br.readLine()) != null){
			System.out.println(readLine);
		}
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

5. file buffer단위 읽기

 - file을 한 줄씩 읽으면 매우 편하지만 readline으로 읽게되면 CR/LF와 같은 문자를 못읽을 수도 있다.

   그래서 특정 bytes의 크기만큼의 buffer를 선언한 후 file을 읽을 경우가 있다.

   

public void getBytesFromFile(String dirRoot){
	File file = new File(dirRoot+"\\sample1.txt");
	try {
		FileInputStream fis = new FileInputStream(file);
		byte buffer[] = new byte[1024];
		while(fis.read(buffer) != -1){
			System.out.print(new String(buffer));
		}
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

 

6. file size 구하기

 - file size는 length() 메소드를 통해 구할 수 있다. 단위는 바이트 임을 명심하자

 

public void getFilesOverSize(String dirRoot){
	System.out.println("2Kbyte 넘는 것만 출력");
	File dir = new File(dirRoot);
	String tempFileName;
	if(dir.exists() && dir.isDirectory()){		//존재하면서 디렉토리일 경우
		for(File file : dir.listFiles()){
			long fileSize = file.length();
			System.out.println(fileSize);
		}
	}
}

'IT > Java' 카테고리의 다른 글

ArrayList 문자열, 객체 정렬  (0) 2019.08.28
Java Socket File 전송  (1) 2019.07.03
BubbleSort 및 ArrayList, String API 요약  (0) 2018.05.08
자바에서 XML다루기(2)  (0) 2015.11.13
객체지향언어 및 객체 개념  (0) 2015.11.13