File 클래스

2021. 8. 2. 03:06코딩

0802 자바 실습1 

File 클래스를 이용하여 폴더 내의 파일 출력하기 

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


public class FileExample {
	public static void main(String[] args) throws Exception {
		File dir = new File("C:/Temp/images");
		File file1 = new File("C:/Temp/file1.txt");
		File file2 = new File("C:/Temp/file2.txt");
		File file3 = new File("C:/Temp/file3.txt");
		
		if(dir.exists()==false) {dir.mkdirs();}
		if(file1.exists()==false) {file1.createNewFile();}
		if(file2.exists()==false) {file2.createNewFile();}
		if(file3.exists()==false) {file3.createNewFile();}
		
		File temp = new File("C:/Temp");
		File[] contents=temp.listFiles();
		
		System.out.println("시간\t\t\t\t형태\t\t크기\t이름");
		System.out.println("__________________________________________________");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a HH:mm");
		for(File file : contents) { 
			System.out.println(sdf.format(new Date(file.lastModified())));
			if(file.isDirectory()) {
				System.out.println("\t<DIR>\t\t\t"+file.getName());
			} else {
				System.out.println("\t\t\t"+file.length()+"\t"+file.getName());
			}
			System.out.println();
		}
	}
	

}

[실행 결과]

<DIR> 2020

2021-07-07 오후 22:31
<DIR> AUtempR

2021-08-02 오전 02:15
113 file1.txt

2021-08-02 오전 02:16
120 file2.txt

2021-08-02 오전 02:17
91 file3.txt

2021-08-02 오전 02:14
<DIR> images

2021-08-02 오전 02:14
<DIR> 동고비

(내가 실습을 위해 생성한 파일명은 images 이고, file1~3 txt 파일이다) 

<DIR>이 폴더이다. 


코드를 한 줄씩 뜯어보자. 

import java.io.File; // java.io(입출력)패키지 안에 있는 File 클래스. 파일 또는 폴더에 대한 정보를 제공하는 클래스 
import java.text.SimpleDateFormat; // java.text 패키지 안에 있는 날짜 출력 클래스 
import java.util.Date; // java.util 패키지 안에 있는 Date 클래스. 자바에서 날짜 데이터를 생성하거나 조작 


public class FileExample {
public static void main(String[] args) throws Exception {

// 메인함수에 Exception(예외)가 붙는 경우는 처음 보았다. 그리고 예외처리인데 try~catch구문도 없고.. 
File dir = new File("C:/Temp/images"); // 디렉토리(폴더) 객체 생성하기 (디렉토리(파일) 이름이 images) 

images폴더를 파일 객체화 
File file1 = new File("C:/Temp/file1.txt"); // 파일 객체 생성하기 (파일 이름이 file1.txt) 
File file2 = new File("C:/Temp/file2.txt"); // 파일 객체 생성하기 (파일 이름이 file2.txt) 
File file3 = new File("C:/Temp/file3.txt"); // 파일 객체 생성하기 (파일 이름이 file3.txt) 


if(dir.exists()==false) {dir.mkdirs();} // 디렉토리(폴더)가 존재하지 않는다면 디렉토리(파일)을 생성해라if(file1.exists()==false) {file1.createNewFile();} // 파일1이 존재하지 않는다면 파일1을 생성해라 
if(file2.exists()==false) {file2.createNewFile();} // 파일2가 존재하지 않는다면 파일2를 생성해라 
if(file3.exists()==false) {file3.createNewFile();} // 파일3이 존재하지 않는다면 파일3을 생성해라 

File temp = new File("C:/Temp"); // C:Temp 폴더의 내용 목록을 
File[] contents=temp.listFiles(); // File 배열로 받는다. 

System.out.println("시간\t\t\t\t형태\t\t크기\t이름");
System.out.println("__________________________________________________");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a HH:mm"); // 날짜 데이터 포맷 설정

여기서 a는 오전/오후를 나타내는 것 같다. 날짜 데이터 포맷을 sdf 변수에 저장한다. 

 

// 향상된 for문을 이용하여 Temp 폴더 내의 정보를 받아오자 
for(File file : contents) { // 향상된 for문을 이용한다 (대입받을 변수명 file : 배열명 contenst) 
System.out.println(sdf.format(new Date(file.lastModified()))); // lastModified() 메소드를 호출하여 일자의 long()을 얻는다. lastModified의 리턴 타입은 long이다. 
if(file.isDirectory()) { // 폴더 내에 파일이 존재하는 경우 true 리턴. 
System.out.println("\t<DIR>\t\t\t"+file.getName());
} else { // 그렇지 않다면 파일의 이름을 가져와서 출력 
System.out.println("\t\t\t"+file.length()+"\t"+file.getName());
}
System.out.println();
}
}


}

 

think ) 

1. 윈도우 C:\Temp 폴더가 무엇일까? 

임시파일 폴더이다. 컴퓨터를 사용하다 보면 용량이 큰 프로그램을 어쩔 수 없이 사용해야 하기 때문에 설치하는 경우가 발생하게 됨. 프로그램이 설치되거나 실행중에 임시적으로 필요한 파일을 생성하는 곳. 이곳에 시스템을 설치한 게 아니라면 삭제해도 무방하다고 한다. 

 

2. public static void main(String[] args) throws Exception 

Main 함수를 선언하는 문장에서 Exception 예외처리를 추가한 문장은 처음 보았다.

내가 아는 형식은 

public static void main(String[] args){ 

try { } 

catch { } 

} 이런 식인데, 위의 코드에서는 Exception을 메인함수 선언부에서 바로 선언하였고, try~catch문을 이용하지도 않았다. 왜 그럴까? -- 그리고 따지면 if~else도 예외처리의 일종이긴 하다만 ... 

 

studied by brandy