Back to the Java

파일 입출력 클래스 / FileInput/OutputStream / FileReader/FileWriter

Backcoder 2022. 7. 8. 21:38

< 파일 입출력 > 

FileInputSteram 1BYTE 단위 
FileOutputStream

FileReader 2BYTE 단위 
FileWriter 

- 입력은 입력끼리 똑같고 출력은 출력끼리 똑같다. 
- 메소드명도 똑같다. 입력은 read 출력은 write 
- 1BYTE(키보드 하나) / 2BYTE(문자=>한글가능) 차이 
- 입력은 파일 없으면 만들어서 입력(자동) 
- 출력은 파일 없으면 만들어서 출력 
- 주의! 출력 기존파일이 있으면 
 생성자 두번째 파라미터에 기본 default 가 false 로잡혀있어서 
 있던거 지우고 덮어써버린다. 

=> true 로 바꾸면 원래 파일에 새로운내용을 추가만 한다. 
    안전하게 true로 바꿔서 사용하자. 




< FileInputStream 클래스 > 
- IOException / FileNotFoundException 잡아야한다. 
   (IO 잡으면 하위클래스인 FNFException 도 잡힌다. ) 

 - 파일 내용 입력 / 1BYTE단위 
  
FileInputStream fi = new FileInputStream(/현재디렉토리생략가능/"입력파일명");
  
int result = fi .read( );   => 파일내용 첫BYTE 입력 // 1BYTE 라서 영문이나 숫자나 가능 

< 파일 끝까지 다 읽게하기 반복문 > EOF = -1 이용  (EndOfFile) => -1 

FileinputStream fi = null;      밖에서 선언해주고 
try{ 
fi = new FIleInputStream( ) ;       생성은 안에서 해주면 
result => -1 ( End of File(EOF) )     => 선언해둔 fi 가 전체에 적용되게 하는 스킬
while(true){ int result = fi.read( ); 
if(result == -1){break;}} } 
catch( ){ }

다 쓰고나면 꼭 닫아줘야 한다. 

fi. close( );       - IOException 

(- java.io 클래스들은 사실상 거의 다 IOException 을 처리해줘야한다.) 

///


< FileOutputStream > 출력 
(BYTE 단위)
마찬가지로 하는데, 출력이 가능한 파일이어야지 
그래서 클래스 쓸때는 먼저 
if ( File.canwrite  해서 확인해주는게 좋은코드다) 

FileOutputStream fi = null; 
try{ 
fi  new FileOutputStream("출력파일명"); 
fi.write(65); => 'A' 
fi.write(97); => 'a' 
fi.write(10); => \n 엔터 } 
catch( ) { } 

 

 

=========================================================================

 


< FileReader / FileWriter > 
FileReader fi = null; 
try{  
fi = new FileReader("파일명"); 
while(true){
int result = fi.read( ); 

if( result == -1 ){ break ; } 
   } //try 

 } catch ( ){ } 
finally { fi.close(); } 

 

2BYTE 씩! 한글가능  

// int 로 반환 (유니코드) 
// 1BYTE(FIleInputStream 일때도 int 인데, 이땐 126까지만 되는 askii 코드 
// 2BYTE(FileReader) 로 되면서 int 인데, 이번에 2BYTE 까지 되는 유니코드 
즉, 한글등 한글자를 다 담을 수 있는 입력클래스다.  

어쨋든 FileReader 자체로 쓸때는 
hasNext next 같은 Scanner 메소드가 없기때문에 
파일 다 읽었을때를 말해주는 코드 -1 을 이용해서 
break를 걸고, while true 문으로 다 읽어준다. 
 
- Writer 도 마찬가지다. 

FileWriter fi = null; 
try{ 
fi = new FileWriter("파일경로 + 이름", true); 

fo.write(65);
fo.write(97);
fo.write("가나다");
fo.write('z');

finally { fo.close() } 

 

==================================

< 정리 > 

 

[ 텍스트 => 파일화 ] 
String input = "텍스트";
FileWriter fw = new FileWriter(파일경로 + 파일명);
fw.write(input); 
fw.close();


[ 파일 => 텍스트 ] 
String encodText = ""; 
String fileText = "";
FileReader fr;
try {
fr = new FileReader(textfile);
Scanner sc = new Scanner(fr); 
while(sc.hasNextLine()) {
mytext += sc.nextLine();
}       
encodText = URLEncoder.encode(fileText, "UTF-8"); 
} catch (Exception e) {
e1.printStackTrace();
}finally{ fr.close();} 

 

 

 

[ 확장자 뽑기 split ] 
String[] file_split = filelist[i].split("\\.");
String ext = file_split[file_split.length-1];