JAVA

[JAVA] 입출력 스트림 ⑥ 파일 제어 및 디렉토리

해니01_15 2023. 3. 13. 18:32

<파일 제어>


파일 클래스 : 프로그래밍 언어에서 파일과 관련된 작업을 수행할 때 사용되는 클래스
파일 존재 : f.exists()
파일 절대경로 : f.getAbsolutePath()
파일명 : f.getName()
파일 크기 : f.length()
파일 읽기가능 : f.canRead()
파일 쓰기가능 : f.canWrite()
파일 실행가능 : f.canExecute()
파일 형태가 맞는지 : f.isFile()
숨김파일인지 확인 : f.isHidden()
파일 생성 : f.createNewFile()
파일/디렉토리 삭제 : f.delete()
디렉토리가 맞는지 : dir.isDirectory()
디렉토리 생성 : dir2.mkdir()

 

package 입출력2;

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

public class FileTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		// 파라미촐 진행한 바일이 없어도 file 경로는 정상적으로 생성된다 .

		File f = new File("src/입출력스트림/files/a.txt");
		System.out.println("파일 존재 : " + f.exists());
		System.out.println("파일 절대 경로 : " + f.getAbsolutePath());
		System.out.println("파일명 : " + f.getName());
		System.out.println("파일 크기 : " + f.length());
		System.out.println("파일 읽기 기능 : " + f.canRead());
		System.out.println("파일 쓰기 기능 : " + f.canWrite());
		System.out.println("파일 실행 기능 : " + f.canExecute());
		System.out.println("파일이냐?: " + f.isFile());
		System.out.println("숨신 파일이냐?  " + f.isHidden());

		File f2 = new File("src/입출력스트림/files/xxx1.txt");
		if (f2.exists() == false) {
			try {
				f2.createNewFile();
				System.out.println("파일 생성 됨");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		f2.delete(); // 파일 삭제
	}
}

 

파일클래스 관리와 비슷하게 디렉토리 역시 메소드를 이용해서 사용 가능하다. 

package 입출력2;

import java.io.File;

public class DirTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		File dir = new File("src/입출력/files");
		System.out.println("디렉토리 존재 : " + dir.exists());
		System.out.println("디렉토리 맞나? : " + dir.isDirectory());
		System.out.println("현재 작업 디렉토리 :" + dir.getAbsolutePath());
		System.out.println("파일목록");

		String[] files = dir.list();
		// dir.list() : 디렉토리에 관한 파일 목록의 파일명들

		for (String fname : files) {
			System.out.println(fname);
		}
		
		File dir2 = new File("src/입출력/files/memo");
		if (dir2.exists() == false) {
			dir2.mkdir(); //디렉토리 생성 
			System.out.println("memo 디렉토리 생성 됨 ");

		}
		dir2.delete(); //디렉토리 삭제
	}

}