Backend/JAVA_Basic

26. JAVA, File 클래스 (input, output)

개발개발빈이 2022. 6. 9. 19:29

○ File 클래스

    - 파일과 관련된 정보를 알 수 있다(파일명, 크기, 확장자명, 파일타입)

    - 파일명 : getName()

    - 파일크기 : length()

    - 파일삭제 : delete()

String pathname="C:/java202202/frontend/images/63367.jpg"; //경로+파일명

File file = new File(pathname);
			
if(file.exists()) {
    System.out.println("파일이 있습니다");

    long filesize = file.length();
    System.out.println("파일크기 : " + filesize + "byte");         //① 기본단위 바이트
    System.out.println("파일크기 : " + filesize/1024 + "KB");      //② KB
    System.out.println("파일크기 : " + filesize/1024/1024 + "MB"); //③ MB

    String filename = file.getName();
    System.out.println("파일이름 : " + filename);

    //파일명과 확장명을 분리해서 출력		
    //파일명: 63367, 확장명: jpg
    int dot = filename.lastIndexOf("."); //마지막 .의 위치
    String name=filename.substring(0, dot);
    String ext=filename.substring(dot+1);
    System.out.println("파일명 : " + name); 
    System.out.println("확장명 : " + ext); 

    //파일삭제
    if(file.delete()) {
        System.out.println(filename + " 파일이 삭제 되었습니다");
    }else {
        System.out.println(filename + " 파일이 삭제가 실패했습니다");
    }

}else {
    System.out.println("파일이 없습니다");
}

 

○ Input

    - 파일(.txt) 입력

        ① byte기반 : FilterInputStream → 한글깨짐

FileInputStream fis=null;

try {

    String filename="C:/java202202/harry.txt";
    fis=new FileInputStream(filename);

    while(true) {
        int data=fis.read(); //1바이트 가져오기
        if(data==-1) {  //파일의 끝(End of File)인지? (read()에서 파일의 끝이면 -1을 반환)
            break;
        }
        System.out.printf("%d", data);	//숫자로 나옴
        System.out.printf("%c", data);	//문자형으로 나옴
    }//while end

}catch (Exception e) {
    System.out.println("파일 읽기 실패:" + e);
}finally {
    //자원 반납
    try {
        if(fis!=null) {	fis.close();}
    } catch (Exception e) {}
}//try end

        ② char 기반 : FileReader → 한글 안 깨짐

FileReader fr=null;

try {

    String filename="C:/java202202/harry.txt";
    fr=new FileReader(filename);

    while(true) {
        int data = fr.read();
        if(data==-1) {
            break;
        }
        System.out.printf("%c", data);
    }//while end

}catch (Exception e) {
    System.out.println("파일 읽기 실패:" + e);
}finally {
    //자원 반납
    try {
        if(fr!=null) {	fr.close();	}
    } catch (Exception e) {}
}//try end

 

        ③ 메모장 파일의 내용을 엔터 단위로 가져오기 : BufferedReader

             - Reader계열이라서 char(2바이트씩) 기반으로 불러옴

             - enter를 기준으로 불러올 수 있게 해주는 함수 있음 (리턴형 String, 파일의 끝을 만나면 null 반환)

import java.io.BufferedReader;
import java.io.FileReader;

public class Test03_input {

	public static void main(String[] args) {
		
		FileReader fr=null;
		BufferedReader br=null;
		
		try {
			
			String filename="C:/java202202/harry.txt";
			
			// 1)파일 가져오기
			fr=new FileReader(filename);
			
			// 2)파일 내용 읽기
			br=new BufferedReader(fr);
			
			int num=0; //행번호
			
			while(true) {
				String line= br.readLine(); // 3)엔터(\n)을 기준으로 한줄씩 가져오기
				if(line==null) {            // 파일의 끝(EOF)인지? 
					break;
				}
				System.out.printf("%d %s\n", ++num, line);		
			
				//20행마다 밑줄 긋기
				if(num%20==0) {
					System.out.println("-------------------------------");
				}
						
			}//while end
						
		}catch (Exception e) {
			System.out.println("파일 읽기 실패:" + e);
		}finally {
			
			//자원 반납 순서 주의 (br먼저!)
			try {
				if(br!=null) {	br.close();	}
			} catch (Exception e) {}
			
			try {
				if(fr!=null) {	fr.close();	}
			} catch (Exception e) {}
		
		}//try end		
		
	}//main() end

}//class end

○ output

    - 메모장 파일에 출력하기 (FileWriter 클래스)

    - 출력파일이 없으면 생성되고, 있으면 덮어쓰기(overwrite) 또는 추가(append)

        ① FileWriter(filename, true) : append모드

        ② FileWriter(filename, false) : overwrite모드

import java.io.FileWriter;
import java.io.PrintWriter;

public class Test04_output {

	public static void main(String[] args) {

		FileWriter fw=null;
		PrintWriter out=null;
		
		try {
			
			// sungjuk.txt
            // → 없으면 파일은 생성된다
			// → 있으면 덮어쓰기(overwrite) 또는 추가(append)
			String filename="C:/java202202/sungjuk.txt";
			
			fw = new FileWriter(filename, false); //false: overwrite모드
			out = new PrintWriter(fw, true);      //true: autoFlush(필수사항)
			
			out.println("무궁화, 95, 90, 100");
			out.println("홍길동, 100, 100, 100");
			out.println("라일락, 90, 95, 35");
			out.println("개나리, 85, 70, 75");
			out.println("진달래, 35, 40, 60");

			System.out.println("sungjuk.txt 데이터 파일 완성");		
			
		} catch (Exception e) {
			System.out.println("파일 쓰기 실패:" + e);
		}finally {		
			//자원 반납
			try {
				if(out!=null) {	out.close(); }
			} catch (Exception e) {}		
			try {
				if(fw!=null) {	fw.close(); }
			} catch (Exception e) {}		
		}//try end
		
	}//main() end

}//class end

지정된 경로에 txt 파일이 생성됨