본문 바로가기
CLASS/JAVA

#14-3 / Stream 활용법

by eungSe__ 2024. 5. 21.

Reader ,Writer,File -> ASCII 전용
Stream -> 바이너리(이미지 , 동영상, 오디오, pdf,zip 등..) 

Stream은 byte단위로 변환 후 집어넣어야 함!

byte[] data = ag.getBytes();

 

 InputStream(입력) 부모 - 하위: FileInputStream , AudioInputStream, ObjectInputStream..등 자식
 OutputStream(출력) 부모 - 하위: FileOutputStream..등 자식

FileInputStream
FileInputStream : io - buffer 필수
대상 파일을 로드 한 후 해당 내용을 byte로 변환하여 결과 출력 (입력 X) - 걍 출력만 함

available() : 파일 용량 (byte단위) / txt도 마찬가지로 byte 단위로 인식이었다..
public class file12 {
	public static void main(String[] args) {
		try {
			String url = "D:\\webpage\\agree\\src\\main\\java\\io\\agree.txt";
			FileInputStream fs = new FileInputStream(url);
			//available() : 파일 용량
			System.out.println(fs.available()); //byte단위의 크기 출력
			
			byte temp[] = new byte[fs.available()]; //해당 파일의 크기만큼만 담김
			fs.read(temp); //byte 전체를 읽어들임 (꼭 한번 읽어줘야함)
			
			String munja = new String(temp); //문자열로 반영
			System.out.println(munja); //내용 출력
			
			fs.close();
 		}catch(Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

 

⚡ FileOutputStream
대상 파일에 사용자가 입력한 내용을 저장시키는 기능
public class file13 {
	public static void main(String[] args) {
		try {
			String url = "D:\\webpage\\agree\\src\\main\\java\\io\\agree.txt";
			String ag = "[개인정보 보호에 대한 약관55454]" + "\n";
			
			//true : 이어쓰기, false : 덮어쓰기
			FileOutputStream os = new FileOutputStream(url,true);
			byte[] data = ag.getBytes();
			
			os.write(data);
			os.flush(); // flush : Stream에 있는 잔류 byte를 모두 출력 후 빈 공간으로 변경
			os.close();
		}catch(Exception e) {
			System.out.println(e.getMessage());
		}finally {
			
		}

	}
}

 

⚡ 응용
/*
 [응용문제]
 Stream을 이용하여 구구단 8단을 dan.txt로 저장되도록 합니다.
 
 */

public class file14 {

	public static void main(String[] args) throws Exception{
		String url = "D:\\webpage\\agree\\src\\main\\java\\io\\dan.txt";
		
		int num = 8;
		byte data[] = null;
		FileOutputStream op = null;
 		try {
 			Path file = Paths.get(url);
 			Files.createFile(file);
 			
			op = new FileOutputStream(url);
			
			int w=1;
			while(w<=9) {
				String result = num+" * "+w+" = "+num*w+"\n";
				data = result.getBytes();
				
				op.write(data);
				w++;
			}
		}catch(Exception e) {
			System.out.println(e.getMessage());
		}finally {
			op.close();
		}

	}

}

 

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

#15-2 / StreamWriter,StreamReader  (0) 2024.05.22
#15-1 / 이미지(binary)  (0) 2024.05.22
#14-2 / nio  (0) 2024.05.21
#14-1 / FileReader => Buffer  (0) 2024.05.21
#13-4 / I/O 🔥  (0) 2024.05.20