본문 바로가기
JAVA

JAVA_입출력

by haheaven 2021. 11. 4.

스프링 사용위해 복습 

 

 

 

- 바이트 기반 파일 스트림 :  FileInputStream / FileOutputStream

   =>  파일로부터 바이트데이터를 읽고, 파일 쓰는데 사용

 ( 바이트기반보조스트림 :  BufferedInputStream / BufferedOutputStream => 바이트기반스트림 기능 향상시키며 단독사용불가)

 ----관련예제(자주 사용하는 흐름)----

public class FileCopy {
public static void main(String[] args) {
	BufferedInputStream bis = null;
    BufferedOutputStream  bos= null;
    
    try {
    	String folder = "c://java/workspace"; // 임의 경로 
    	String filename = "image.img";        // 읽을 이미지 (해당 클래스와 같은 경로에 있을 경우 파일명만 적어도 읽기 가능)
    	File dir = new File(folder);
    	if ( dir.exists() == false ) {
    		dir.mkdirs();               // 폴더가 없다면 만들기 !!
    	}
    	
    	File file = new File(dir, filename);  // 새롭게 만들곳 
    	
    	bis = new BufferedInputStream(new FileInputStream(filename));  // 기존 이미지 읽기 
    	bos = new BufferedOutputStream(new FileOutputStream(file)); // 기존이미지 복사본만들기 
    
    	//읽을 파일의 바이트 배열 
    	byte[] b = new byte[1024]; 
    	int readCount = 0; // 읽을 바이트 있는지 확인하기 위한 변수 
    	
    	while(true) { // 파일 계속 읽기 위한 무한루프 
    		readCount = bis.read(b);    // b배열 계속 읽기 
    		if (readCount== -1) {       // 파일을 읽다가 읽을게 없으면 -1로 반환이되기 때문에 -1이 되는 순간브레이크로 무한 루프 빠진다.
    			break;
    		}
    		bos.write(b, 0, readCount); // 읽혀지는 동안은 계속 새 폴더에 출력하기 
    	}

    	
    } catch(IOException e) {
		e.printStackTrace();
    	
    }finally {
    	if( bis != null) 
    		try {
				if(bos!= null) bos.close(); 
			    if(bis != null) bis.close();
			} catch(Exception e) {
				e.printStackTrace();
			}
    	}

    	}

}

 

 

- 문자기반스트림 (파일): FileReader / FileWriter  => 파일로부터 텍스트데이터를 읽고, 파일 쓰는데 사용

 ( 문자기반보조스트림 :  BufferedReader / BufferedWriter => 문자기반스트림 기능 향상시키며 단독사용불가)

 ----관련예제(자주 사용하는 흐름)/   바이트 기반 파일입출력과 유사하다 ----

public class FileCopy2 {
public static void main(String[] args) {
	BufferedReader br = null;
    BufferedWriter  bw = null;
    
    try {
    	br = new BufferedReader(new FileReader("test.txt"));  // 기존 텍스트 읽기 
    	bw = new BufferedWriter(new FileWriter("test2.txt")); // 새롭게 쓰기 
    	
    	
    	int readCount = 0;
    	char[] c = new char[1024];
    	
    	while(true) {
    		readCount = br.read(c);  
    		if( readCount == -1 ) { break; }   // 읽다가 line이 null이면 무한루트 빠지기 
    	
    	 bw.write(c, 0, readCount);
    	}
 
    }catch(IOException e) {
    	e.printStackTrace();
    } finally {
    	try {
    		if( br != null) {br.close();}
    		if( bw != null) {bw.close();}
    	} catch(IOException e) {
    		e.printStackTrace();
    	}
    }
   

	
	}
}

 

- BufferedReader의 readLine() 사용 예제 

public class FileCopy3 {
public static void main(String[] args) {
	BufferedReader br = null;
  
    
    try {
    	br = new BufferedReader(new FileReader("test.txt"));  // 텍스트 읽기 
    	StringBuilder sb =new StringBuilder();  // 텍스트전부 읽어줄 빌더  객체 생성 
    	
    	String line = "";
    	while(true) {    // 텍스트 계속읽을 무한루프 
    		line = br.readLine();
    		if( line == null ){ break; }  // 읽을 라인 없으면 반환 
    		
    		sb.append(line); // 읽은 텍스트는 빌더에 계속 추가하기 
    	}
    		System.out.println(sb.toString());
 
    }catch(IOException e) {
    	e.printStackTrace();
    } finally {
    	try {
    		if( br != null) {br.close();}
    	} catch(IOException e) {
    		e.printStackTrace();
    	}
    }
   
	}
}

 

 

 

--> 자주 사용되는 흐름이므로 잊지말자!

'JAVA' 카테고리의 다른 글

JAVA_BufferedReader, StringTokenizer, BufferedWriter  (0) 2021.10.17
JAVA_람다식(Rambda expression)  (0) 2021.08.10
JAVA_Thread1  (0) 2021.08.08
JAVA_제네릭, 열거형, 애너테이션  (0) 2021.08.07
JAVA_컬렉션 프레임워크(Set, Map)  (0) 2021.08.06

댓글