쌍용교육(JAVA)/JAVA

쌍용교육 -JAVA 수업 15일차 File

구 승 2024. 4. 12. 08:46
package kr.s28.iostream;
import java.io.File;

public class FileMain01 {
	public static void main(String[] args) {
		String path = "C:\\\\"; //역슬레쉬는 디렉토리 구분자 , 원랜 하나지만 자바에서는 특수문자로 사용하기 때문에 역슬레쉬는 2번 사용

		File f = new File(path);

		// 존재하지않거나       디렉토리가 아니면 프로그램 종료 
		if(!f.exists()|| !f.isDirectory()){
			System.out.println("유효하지 않은 디렉토리입니다.");
			System.exit(0);//프로그램 종료    
		}
		//지정한 디렉토리의 하위 디렉토리와  파일 정보를 반환
		File[] files = f.listFiles();
		for(int i =0 ; i <files.length ; i ++) {
			File f2 = files[i];//f2가 하위 디렉토리와 파일정보를 받음
			if(f2.isDirectory()) {//디렉토리인지 확인하는 함수
				System.out.println("["+f2.getName()+"]");//getName을 써서 디렉토리명을 
			}else {//반대로 파일인경우
				System.out.print(f2.getName());//getName을 써서 파일명을
				//파일은 디렉토리와 다르게 용량의 개념이 있음
				System.out.printf("(%,dbytes)%n",f2.length());//length로 길이 즉 용량을 구함.
			}
		}
	}
}

[$RECYCLE.BIN]
[$WinREAgent]
[Boot]
bootmgr(415,550bytes)
BOOTNXT(1bytes)
BOOTSECT.BAK(8,192bytes)
[Daum Games]
[Documents and Settings]
DumpStack.log.tmp(8,192bytes)
[javaWork]
msdia80.dll(904,704bytes)
[Nexon]
[OneDriveTemp]
[oraclexe]
pagefile.sys(5,260,720,128bytes)
[Program Files]
[Program Files (x86)]
[ProgramData]
[Recovery]
[Riot Games]
swapfile.sys(16,777,216bytes)
[System Volume Information]
[Temp]
[Users]
[Windows]

package kr.s28.iostream;
import java.io.File;
import java.io.IOException;

public class FileMain02 {
	public static void main(String[] args) {
		//절대경로
		//String path ="C:\\\\javaWork\\\\sample.txt";//sample.txt를 만들고 싶을 때 역슬레쉬를하고 절대경로 뒤에 추가한다.
	
		//상대경로
		String path = "sample.txt"; //파일명만 명시
		
		File f1 = new File(path);
		System.out.println("====파일 생성====");
		try {
			/*
			 * 제공된 경로를 기반으로 파일을 생성. 파일이 생성되면 true를 반환, 생성되지 않으면 false를 반환
			 * 경로가 잘못되면 IOException 발생
			 * (절대경로 일 경우)true가 나오면 javawork에 들어가보면 sample.txt 파일이 생겨있음.
			 * (상대경로 일 정우)C:\\javaWork\\workspace\\ch01_Java\\sample.txt 위치에 파일이 생김(탐색기에만 보이고 이클립스에는 새로고침을 해야 보임<ch01.java->Refresh>)
			 * 한 번 더 실행하면 이미 있는 파일이기 때문에 덮어씌우는 것이 아닌 그냥 false가 발생.
			 */
			System.out.println(f1.createNewFile());//createNewFile 새로운 파일을 만드는 함수. 그치만 그냥쓰면 IOException에러나 생길 수 있어서 try catch가 필요
		}catch(IOException e) {
			e.printStackTrace();
		}
		
		System.out.println("===파일 정보 ===");
		System.out.println("절대경로 : "+ f1.getAbsolutePath());
		System.out.println("상대경로 : "+ f1.getPath());
		System.out.println("디렉토리명 : "+f1.getParent());//상대경로만 지정할 시null값이 나오는 이유는 경로지정시 파일명만 지정을하고 디렉토리명을 지정을하지 않아서.
		System.out.println("파일명 : "+f1.getName());
	}
}

====파일 생성====
true
===파일 정보 ===
절대경로 : C:\\javaWork\\workspace\\ch01_Java\\sample.txt
상대경로 : sample.txt
디렉토리명 : null
파일명 : sample.txt

package kr.s28.iostream;
import java.io.File;

public class FileMain03 {
	public static void main(String[] args) {
		//상대경로
		String path = "sample.txt";//원래 파일명
		String new_path = "example.txt";//새 파일명
		
		File f1 = new File(path);
		System.out.println("===파일명 변경===");
		File f2 = new File(new_path);
		//파일명을 변경할 수 있으면 변경하고 true 반환, 변경이 불가능하면 false를 반환
		System.out.println(f1.renameTo(f2));//실행 후 한 번 더 실행하면 이미 변경되었기 때문에 false로 나온다. renameTo안에는 객체명만 들어갈 수 있다.
	}
}

===파일명 변경===
true

package kr.s28.iostream;

import java.io.File;

public class FileMain04 {
	public static void main(String[] args) {
		//상대경로
		String path = "example.txt"; //기존에 있는 파일명을 명시
		
		File f1 = new File(path);
		
		System.out.println("===파일삭제===");
		
		//delete():삭제할 수 있으면 삭제하고 true를 반환. 삭제가 불가능하면 false를 반환
		if(f1.delete()) {
			System.out.println(f1.getName()+ "파일삭제");
		}else {
			System.out.println("파일을 삭제하지 못했습니다.");//한 번 더 실행하면 이미 삭제되었기 떄문에 else로 빠진다.
		}
	}
}

===파일삭제===
example.txt파일삭제

package kr.s28.iostream;
import java.io.File;

public class FileMain05 {
	public static void main(String[] args) {
		String path = "C:\\\\javaWork//javaSample";
		
		File f1 = new File(path);
		
		System.out.println("===디렉토리 생성 ===");
		//디렉토리를 생성할 수 있으면 true , 생성할 수 없으면 false 반환
		System.out.println(f1.mkdir());// 한 번 더 실행하면 false
		
	}
}
  
===디렉토리 생성 ===
true

package kr.s28.iostream;
import java.io.File;
public class FileMain06 {
	public static void main(String[] args) {
		//절대경로
		String path = "C:\\\\javaWork\\\\javaSample";
		
		File f1 = new File(path);
		System.out.println("==디렉토리 삭제==");
		if(f1.delete()) {
			System.out.println(f1.getName()+"디렉토리 삭제");
		}else {
			System.out.println("디렉토리를 삭제할 수 없습니다.");
		}
	}
}

==디렉토리 삭제==
javaSample디렉토리 삭제