JAVA/수업

T01FileTest File 객체

lavender1122 2024. 1. 31. 21:07

File 클래스

  • 시스템에 있는 파일이나 디렉토리 추상화 클래스
  • 파일의 생성, 삭제, 크기, 읽기 또는 쓰기 모드 등과 같은 파일 자체 관리하기 위한 클래스

new File(String파일 또는 경로명)

1. new File(String 파일 또는 경로명)

File file = new File("d:/D_Other/test.txt");
File file2 = new File("d:/D_Other");

2. new File(File parent, String child)
→ 'parent' 디렉토리 안에 있는 'child' 파일 또는 디렉토리를 위한 파일 객체 생성

//file2 = "d:/D_Other"
//"d:/D_Other" + "text.txt"
File file3 = new File(file2, "text.txt");

3.new File(String parent, String child)

File file4 = new File(".\\D_Oher\\test\\..", "test.txt");

 .getName()

  •  파일이름 알기 
System.out.println("파일명 : "+ file.getName());

System.out.println(file2.getName() + "은");

.isFile()

  •  폴더 있으면 true 없으면 false
System.out.println("파일 여부 :" + file.isFile());

.isDirectory()

  •  디렉토리 있으면 true 없으면 false
System.out.println("디렉토리(폴더) 여부 :" + file.isDirectory());

if(file2.isFile()) {
	System.out.println("파일입니다.");
}else if(file2.isDirectory()) {
	System.out.println("디렉토리(폴더) 입니다.");
}


.isFile()

  •  파일 있으면 true 없으면 false
System.out.println("파일 여부 :" + file.isFile());
System.out.println("디렉토리(폴더) 여부 :" + file.isDirectory());

.length() 

  • 파일용량 사이즈 아는 방법
System.out.println(file3.getName() + "의 용량 크기 : " + file3.length()+ "(bytes)");

.getAbsolutePath() 절대경로

  • 파일의 root부터 해당 파일까지의 전체 경로(URL)의미
  • 파일 경로 지정하는데 내가 어디 있든지 파일 경로가 변치 않음
  • 장점 : 어느 곳에서든 경로에 접근할 수 있음
  • 단점 : 경로 변경되면 경로를 일일히 수정해야함
  • 용도 : CDN(콘텐츠 전송 네크워크)을 사용하거나, 웹에 올려진 미디어 사용할 때
System.out.println("절대 경로 : " + file4.getAbsolutePath());

.getPath() 상대경로

  • 현재 디렉터리에 상대적일 수 있음
  • 장점 : 주소나 프로젝트 디렉토리 위치가 바꿔어도 내부 구조만 그대로라면 수정 없이 그대로 사용
  • 단점 : 자기자신이 기준이기 때문에 자기 자신의 위치가 바뀌는것에 취약
  • 용도: 디렉토리 내부에서 모듀을 연결하거나, 다른 파일을 import하는 경우 사용
기호 의미
/ root
./ 현재위치
../ 상위경로

 

System.out.println("경로 : "+ file4.getPath());

 

더보기

1. 우리가 c.txt에서 작업하고 있을 때 a.txt파일로 이동하고 싶다면?

답 : ../../a/a.txt

 

2. a.txt에서 c.txt를 향하고 싶으면?

답 : ../c/inner_C/c.txt

3. temp를 root로 가정했을 때 , root를 기준으로 a.txt의 위치를 나타내고 싶다면?

답:/a/a.txt

.getCanonicalPath() 표준경로

  • .(점)빠짐
  • 실제 의미있는 경로를 계산을 해서 알려줌
System.out.println("표준 경로 : "+ file4.getCanonicalPath());


디렉토리(폴더)만들기

  • 만들수 있는 권한이 있는 폴더에 만들수 있음

.mkdir()

  • File 객체의 경로 중 마지막 위치의 디렉토리 만듬
    중간의 경로가 모두 미리 만들어야 함
  • 만들기 성공하면 true, 폴더가 존재하면 디렉토리 생성하지 않고 false

1.객체 생성

 File file5 = new File("d:/D_Other/연습용");

2. if문사용

 if(file5.mkdir()) {
			 System.out.println(file5.getName() + "만들기 성공!");
		 }else {
			 System.out.println(file5.getName() +" 만들기 실패!!");
		 }

.mkdirs()

  • 중간의 경로가 없으면 중간의 경로도 새롭게 생성한 후 마지막 위치의 디렉토리를 만들어 줌
  • 만들기 성공하면 true, 폴더가 존재하면 디렉토리 생성하지 않고 false

1. 객체생성

File file6 = new File("d:/D_Other/test/java/src");

2.if문 사용

if(file6.mkdirs()) {
  System.out.println(file6.getName() + "만들기 성공!");
}else {
  System.out.println(file6.getName() +" 만들기 실패!!");
 }


원본

더보기
package kr.or.ddit.basic;

import java.io.File;
import java.io.IOException;

public class T01FileTest {

	public static void main(String[] args) throws IOException {
		//File 객체 만들기 연습
		
		//1. new File(String 파일 도는 경로명)
		// 	=> 디렉토리와 디렉토리 사이 또는 디렉토리와 파일명 사이의 구분문자는 '\'를
		//		사용하거나 '/'를 사용할 수 있다.
		//		\ 단점 : 이스케이프로 인식할 수 있어서 한번더 써야함 \\
		//	핸들링할수 있는 객체를 만드는것 , 파일생성하는것이 아님
		File file = new File("d:/D_Other/test.txt");
		//.getName() : 이름 알수 있음
		System.out.println("파일명 : "+ file.getName());
		//.isDirectory() : 디렉토리  알 수 있음 있으면 true 없으면 flase
		System.out.println("파일 여부 :" + file.isFile());
		System.out.println("디렉토리(폴더) 여부 :" + file.isDirectory());
		System.out.println("--------------------------------------------------");

		File file2 = new File("d:/D_Other");
		System.out.println(file2.getName() + "은");
		if(file2.isFile()) {
			System.out.println("파일입니다.");
		}else if(file2.isDirectory()) {
			System.out.println("디렉토리(폴더) 입니다.");
		}
		System.out.println("---------------------------------------------------");
		
		//2. new File(File parent, String child)
		// => 'parent' 디렉토리 안에 있는 'child' 파일 또는 디렉토리를 위한 파일 객체 생성
		
		//file3 = "d:/D_Other"+ "text.txt" 
		File file3 = new File(file2, "text.txt");
		//해당 파일 사이즈 아는 법 :file3.length()
		System.out.println(file3.getName() + "의 용량 크기 : " + file3.length()+ "(bytes)");
		
		//3. new File(String parent, String child)
		// ./ 현재경로 => 내가 작성하고 있는 자바 프로젝트
		// ../ 상위 경로
		File file4 = new File(".\\D_Oher\\test\\..", "test.txt");
		//절대경로 : 파일 경로 지정하는데 내가 어디 있든지 파일 경로가 변치않음
		//        윈도우에서는 절대경로 처음 에는 드라이브 문자(이름) 나와야함
		//상대경로 : 내가 어디 있는지 경로가 바꿈 시작을 . 이나 .. 을 시작함
		//		  장점: 파일만 복붙해도 경로가 ...
		System.out.println("절대 경로 : " + file4.getAbsolutePath());
		//경로 : 생성자 넣은것을 그래도 넣음
		//getPath() 파라미터 그대로 가져오는것
		System.out.println("경로 : "+ file4.getPath());
		//표준경로: . 빠짐 / 실제 의미하는 경로를 계산을 해서 알려줌
		System.out.println("표준 경로 : "+ file4.getCanonicalPath());
		
		/*
		 * 디렉토리(폴더) 만들기
		 * 만들수 있는 권한이 있는 폴더에 만들수 있다
		 * 
		 * 1. mkdir() => File 객체의 경로중 마지막 위치의 디렉토리를 만든다.
		 * 				 중간의 경로가 모두 미리 만들어져 있어야 한다.
		 * 2. mkdirs() => 중간의 경로가 없으면 중간의 경로도 새롭게 생성한 후 마지막 위치의 디렉토리를
		 * 				  만들어 준다.
		 * 		=> 위 두 메서드 모두 만들기를 성공하면 true, 실행하면 false 반환한다.
		 */
		
		 File file5 = new File("d:/D_Other/연습용");
		 if(file5.mkdir()) {
			 System.out.println(file5.getName() + "만들기 성공!");
		 }else {
			 System.out.println(file5.getName() +" 만들기 실패!!");
		 }
		 
		 File file6 = new File("d:/D_Other/test/java/src");
		 if(file6.mkdirs()) {
			 System.out.println(file6.getName() + "만들기 성공!");
		 }else {
			 System.out.println(file6.getName() +" 만들기 실패!!");
		 }
		
	}
}