본문 바로가기
CLASS/JAVA

#13-4 / I/O 🔥

by eungSe__ 2024. 5. 20.

👀 선생님 전체 정리 내용

https://dev-eunse.tistory.com/99

 

👀 내가 해본 전체 정리 내용

https://dev-eunse.tistory.com/92

 

I/O : input/output 

input - 키보드,마우스,Hdd,File ..등

output - 모니터,프린터.. 등

 

java.io > java.nio

 

👀

I/O는 무조건 예외처리를 사용해야한다  - 넣지 않으면 작동불능!

load할 파일명과 경로가 올바른 상황이면 try/그 반대 상황은 catch 🔽

파일 첨부 기능 제작시 주로 사용

public static void main(String[] args) {
   try {//io는 예외처리 필수
	//해당 로드할 파일 properties -> 경로 입력   
	  //서버에 올라가있으면 상대경로 작성 가능    
        FileReader fr = new FileReader("D:\\webpage\\agree\\src\\main\\java\\io\\agree.txt");
    }catch(Exception e) {
        System.out.println(e.getMessage());

    }

}

//or 귀찮으면 아래와같이 작성하기도 함.. 정확한 에러를 찾아낼수 없다는 단점 하지만 그게그거임

public static void main(String[] args) throws Exception{
    FileReader fr = new FileReader("D:\\webpage\\agree\\src\\main\\java\\io\\agree.txt");
}

 

FileReader 

package 우클릭 -> new -> other -> untitled txt file 생성 -> .txt파일

FileReader : 문자 데이터 즉 (ASCII)만 해당 / 읽기

👀주의
읽기 시 for문 사용 x
public static void main(String[] args) {
    try {
        //load할 파일명과 경로가 올바른 상황이면 try/그 반대 상황은 catch
        FileReader fr = new FileReader("파일경로");

        System.out.println(fr.getEncoding()); //해당 파일의 언어셋 확인 : UTF8 출력
        System.out.println(fr.read());//파일용량체크(bit)

        //무한루프로 파일 전체를 읽어 들여야함
        while(true) { 
            int size = fr.read(); //파일을 읽어들임(ASCII)-int로받음
            System.out.println((char)size); 
            if(size == -1) { //해당 파일에 더이상 읽을 내용이 없을 경우
                break;	
            }		
        }
	fr.close(); //파일을 닫아줘야 수정 후 추가 저장 가능

    }catch(Exception e) {
        System.out.println(e.getMessage());
    }

}

 

FileWriter (다른 속성을 가진 ASCII 파일 읽기 및 쓰기)
package 우클릭 -> new -> other -> file 생성 -> .dat파일

👀주의
FileWriter : 문자 데이터 저장파일 ,(ASCII)만 해당 / 쓰기(저장) , new FileWriter은 반복문안에 x
write() : 해당 내용을 저장시키는 메소드
fw.close(); : 파일을 닫지 않으면 저장이 안된다!
this.fw.write(sum + "\n"); : 숫자로는 데이터 저장 x => 문자로만 저장 가능
this.fw = new FileWriter(this.url,true);  => true : 기본 데이터 보존 , false : 새롭게 데이터 삽입 

public static void main(String[] args) throws Exception {
    //--해당 라인 전체를 읽어들이는 방식
    FileReader fr = new FileReader("파일경로");
    Scanner file = new Scanner(fr);

    System.out.println(file.nextLine()); //파일 내용 첫째줄 출력됨
    file.close();
    fr.close(); //닫을땐 역순

    //--새로 내용을 입력하고 저장하는 방식
    FileWriter fw = new FileWriter("파일경로");
    Scanner sc = new Scanner(System.in);
    System.out.println("추가내용 입력 : ");
    //write() : 해당 내용을 저장시키는 메소드
    fw.write(sc.nextLine()); //기존 내용 사라지고 sc로 입력한 값 덮어써짐

    sc.close(); 
    fw.close(); //파일을 닫지 않으면 저장이 안된다!

}

 

⚡ 여러개의 라인이 있는 파일 내용 읽기 및 쓰기
public class file3 {
	public static void main(String[] args){
		String url = "D:\\webpage\\agree\\src\\main\\java\\io\\agree.txt";
		
		try {
			FileReader fr = new FileReader(url);
			Scanner sc = new Scanner(fr);
			
			//그 다음라인에 문자가 있는지 확인 - true or false 출력
			//System.out.println(sc.hasNext());
			
			//for문으로 무한루프 돌릴 시 해당 라인 외의 경고메세지까지 출력이 되어버림
			  //(한바퀴 더돌아감)
			  //for문의 한계...! (do~while,while은 제대로 출력)
			while(sc.hasNext()) { //true or false
				//파일 전체 제대로 출력,공백도 모두 출력
				System.out.println(sc.nextLine()); 
			}

			sc.close();
			fr.close();
			
			//추가 글쓰기
			new file3_box().file_write();	
		}catch(Exception e) {
			
		}
		
	}
}

class file3_box {
	String url = "D:\\webpage\\agree\\src\\main\\java\\io\\agree.txt";
	FileWriter fw = null;
	Scanner sc = null;
	
	public void file_write() throws Exception{
		System.out.println("추가 내용을 입력하세요 : ");
		this.sc = new Scanner(System.in);
		String msg = this.sc.nextLine();
		//true : 기본 데이터 보존 , false : 새롭게 데이터 삽입
		this.fw = new FileWriter(this.url,true); //true 빼면 덮어버림 (false가 기본) !
		
		this.fw.write("\n"+msg); //다음 줄에 입력한 내용이 추가됨
		System.out.println("저장완료되었습니다");
		this.sc.close();
		this.fw.close();
	}
}

 

⚡ File (파일 생성)
File : 실제 경로에서 생성,삭제,다른 경로로 이동,해당파일명이나 속성 변경 에 사용( close() 필요없음 )

.createNewFile();
파일을 생성하는 메소드
실제 디렉토리에 들어가서 확인해야함
public class file4 {
	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder();
		sb.append("D:\\webpage\\agree\\src\\main\\java\\io\\"); //마지막 \\있어야함
		sb.append("member.txt");
		try {
			File f = new File(String.valueOf(sb)); //File : 파일생성파트
			f.createNewFile(); //파일을 생성하는 메소드
		}catch(Exception e) {
			System.out.println(e.getMessage());
		}
	}

}

 

⚡ 응용
writer,reader close - finally{}에 해줘도 됨!!
/*
 [응용문제 - io기초]
 파일은 gugu.txt로 java에서 생성되어야 하며 사용자가 다음과 같이 입력합니다.
 "구구단을 입력하세요 : "
 gugu.txt에 사용자가 입력한 구구단 을 모두 출력하세요.
 예시 )
 6을 입력시
 6*1=6
 ..
 6*9=54
 
 */
public class file5 {

	public static void main(String[] args) {
		String url = "D:\\webpage\\agree\\src\\main\\java\\io\\gugu.txt";
		try{
			File f = new File(url);
			f.createNewFile();
			
			Scanner sc = new Scanner(System.in);
			System.out.println("구구단을 입력하세요 : ");
			int gugu_num = sc.nextInt();
			sc.close();
			
			new file5_write(gugu_num , url);
			
		}catch(Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

class file5_write {
	FileWriter fw = null;
	FileReader fr = null;
	Scanner file = null;
	
	public file5_write(int a , String b) throws Exception {
		try {
			//받아서 쓰기
			this.fw = new FileWriter(b,false);
			int f;
			for(f=1; f<=9; f++) {
				this.fw.write(a +"*"+ f +"="+ a*f + "\n");
			}
			System.out.println("저장이 완료되었습니다");
			this.fw.close();
			
			//읽기->sysout찍기
			this.fr = new FileReader(b);
			this.file = new Scanner(fr);
			
			while(this.file.hasNext()) {
				System.out.println(this.file.nextLine());
			}
		}catch(Exception e2) {
			System.out.println(e2.getMessage());
		}finally {
			file.close();
			fr.close();
		}
	}
	
}

 

'CLASS > JAVA' 카테고리의 다른 글

#14-2 / nio  (0) 2024.05.21
#14-1 / FileReader => Buffer  (0) 2024.05.21
#13-3 / Map클래스배열(Key배열)  (0) 2024.05.20
#13-2 / Thread  (0) 2024.05.20
#13-1 / String, StringBuilder, StringBuffer  (0) 2024.05.20