Java Category/Java

[Java] File과 Files 클래스

ReBugs 2023. 8. 10.

이 게시글은 이것이 자바다(저자 : 신용권, 임경균)의 책과 동영상 강의를 참고하여 개인적으로 정리하는 글임을 알립니다. 


java.io 패키지와 java.nio.file 패키지는 파일과 디렉토리 정보를 가지고 있는 File과 Files 클래스를 제공한다.

Files는 File을 개선한 클래스로, 좀 더 많은 기능을 가지고 있다.

 

File 클래스

File 클래스로부터 File 객체를 생성하는 방법은 아래와 같다.

File file = new File("경로");

경로 구분자는 OS마다 조금씩 다르다.

윈도우에서는 \\ 또는 /를 둘 다 사용할 수 있고, 맥 OS 및 리눅스에서는 /를 사용한다.

 

아래는 윈도우에서 File 객체를 생성하는 코드이다.

File temp = new File("C:/Temp/file.txt");
File temp = new File("C:\\Temp\\file.txt");

File 객체를 생성했다고 해서 파일이나 디렉토리가 생성되는 것은 아니다.

그리고 경로에 실제 파일이나 디렉토리가 없더라도 예외가 발생하지 않는다.

파일이나 디렉토리가 실제 있는지 확인하고 싶다면 File 객체를 생성하고 나서 exists() 메소를 호출해 보면 된다.

boolean isExist = file.exists(); //파일이나 폴더가 존재한다면 true를 리턴

exists() 메소드가 false를 리턴할 경우, 아래 메소드로 파일 또는 폴더를 생성할 수 있다.

출처  : 이것이 자바다 유튜브 동영상 강의

mkdir()과 mkdirs()의 차이
mkdir()는 C:/dir/dir2 경로에 dir 폴더가 있으면 dir2를 생성시킨다. dir 폴더가 없으면 dir2를 생성시키지 못한다.
mkdirs()는 C:/dir/dir2 경로에 없는 폴더를 모두 생성시킨다.

exists() 메소드의 리턴값이 true라면 아래 메소드를 사용할 수 있다.

출처  : 이것이 자바다 유튜브 동영상 강의

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
	
public class FileExample {
	public static void main(String[] args) throws Exception {
		//File 객체 생성
		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(); }

		//Temp 폴더의 내용을 출력
		File temp = new File("C:/Temp");
		File[] contents = temp.listFiles();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a HH:mm");
		for(File file : contents) {
			System.out.printf("%-25s", sdf.format(new Date(file.lastModified())));
			if(file.isDirectory()) {
				System.out.printf("%-10s%-20s", "<DIR>", file.getName());
			} else {
				System.out.printf("%-10s%-20s", file.length(), file.getName());
			}
			System.out.println();
		}
	}
}
/*
2023-07-31 오후 15:02      0         file1.txt           
2023-07-31 오후 15:02      0         file2.txt           
2023-07-31 오후 15:02      0         file3.txt           
2023-07-31 오후 15:02      <DIR>     images              
2023-07-31 오전 03:14      201       object.dat          
2023-07-31 오전 01:56      46        primitive.db        
2023-07-31 오전 02:07      172       printstream.txt     
2023-07-31 오전 01:29      42405     targetFile1.jpg     
2023-07-31 오전 01:29      42405     targetFile2.jpg     
2023-07-30 오후 14:47      42405     test.jpg            
2023-07-31 오전 00:48      43        test.txt            
2023-07-30 오후 13:51      3         test1.db            
2023-07-30 오후 14:03      3         test2.db            
2023-07-30 오후 15:00      42405     test2.jpg    
*/
최근 수정한 날짜 얻기
new Date(file.lastModified())​

위 코드에서 file.lastModified()는 long 타입 값을 리턴하는데, Date()는 이를 날짜로 만든다.

입출력 스트림을 생성할 때 File 객체 활용하기
파일 또는 폴더의 정보를 얻기 위해 File 객체를 단독으로 사용할 수 있지만, 파일 입출력 스트림을 생성할 때 경로 정보를 제공할 목적으로 사용되기도 한다.
//첫 번째 방법
FileInputStream fis = new FileInputStream("C://temp/image.gif");

//두 번째 방법
File file = new File("C://temp/image.gif");
FileInputStream fis = new FileInputStream(file);​

 


 

Files 클래스

Files 클래스는 정적 메소드로 구성되어 있기 때문에 File 클래스처럼 객체를 만들 필요가 없다.

Files의 정적 메소드는 운영체제의 파일 시스템에게 파일 작업을 수행하도록 위임한다.

출처  : 이것이 자바다 유튜브 동영상 강의

이 메소드들은 매개값으로 Path 객체를 받는다.

Path 객체는 파일이나 디렉토리를 찾기 위한 경로 정보를 가지고 있는데, 정적 메소드인 get() 메소드로 아래와 같이 얻을 수 있다.

Path path = Path.get(String first, String...more)

get() 메소드의 매개값은 파일 경로인데, 전체 경로를 한꺼번에 지정해도 되고, 상위 디렉토리와 하위 디렉토리를 나열해서 지정해도 된다.

Path path = Paths.get("C:/Temp/dir/file.txt");
Path path = Paths.get("C:/Temp/dir", "file.txt");
Path path = Paths.get("C:", "Temp", "dir", "file.txt");

 

파일의 경로는 절대 경로와 상대 경로를 모두 사용할 수 있다.

Path path = Paths.get("dir/file.txt");
Path path = Paths.get("./dir/file.txt");

 

현재 위치가 "C:\Temp\dir1"이라면 "C:\Temp\dir2\file.txt"는 아래와 같이 지정이 가능하다.

.이 현재 디렉토리라면 ..은 상위 디렉토리를 뜻한다.

Path path = Paths.get("../dir2/file.txt");

 

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FilesExample {
	public static void main(String[] args) {
		try {
			String data = "" +
					"id: winter\n" +
					"email: winter@mycompany.com\n" +
					"tel: 010-123-1234";
						
			//Path 객체 생성
			Path path = Paths.get("C:/Temp/user.txt");
			
			//파일 생성 및 데이터 저장
			Files.writeString(path, data, Charset.forName("UTF-8"));
					
			//파일 정보 얻기
			System.out.println("파일 유형: " + Files.probeContentType(path)); //대분류/중분류 (MimeType)
			System.out.println("파일 크기: " + Files.size(path) + " bytes");
			
			//파일 읽기
			String content = Files.readString(path, Charset.forName("UTF-8"));
			System.out.println(content);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
/*
파일 유형: text/plain
파일 크기: 56 bytes
id: winter
email: winter@mycompany.com
tel: 010-123-1234
*/

댓글