본문 바로가기
JAVA/IO

[java/File] image File road 정리

by java나유 2022. 6. 27.
  • 이미지 파일은 FileInputStream 을 이용해서 로드해야한다.
  • InputStream is = new FileInputStream("");  가능OK
  • InputStream is = new FileImageInputStream(""); 가능OK //자바 7이전에 많이 사용
  • FileInputStream fs = new FileInputStream("");  가능OK

IOException 위치는 2가지 가능

main에 써줘도되고 catch에 써줘도된다.

또 catch를 2개 추가하여 Exception추가 가능

 

1. 방법

public static void main(String[] args) throws IOException{

2. 방법

public static void main(String[] args)
try {
InputStream is = new FileInputStream("");
}

catch(IOException e){

 

이미지 파일 불러서 한번 출력해보자.

InputStream is = new FileInputStream("C:\\java5\\File_Strame\\src\\img.jpg");
			//InputStream is = new FileImageInputStream(""); 이것도 가능
			//FileInputStream fs = new FileInputStream(""); 이것도 가능
			System.out.println(is.read()); //255:픽셀단위로 읽음(색수치)

System.out.println(is.read()); 로 읽으면 콘솔에 255가 찍히게된다. (이미지 픽셀값)

 

알아두면 좋은 점

  • Stream은 버퍼와 비슷해서 read를 사용하면 비워짐 문서는 관계없음
  • 즉, 한번 읽였으면 이후에 동일한 파일을 사용할 때(ex)복사) 제대로 복사 되지 않음
  • FileOutputStream os = new FileOutputStream("img.jpg") 복사하는 메소드
  • FileOutputStream은 복사할 원본 파일 앞 폴더에 생성된다.

 

InputStream is = new FileInputStream("C:\\java5\\File_Strame\\src\\img.jpg"); //원본파일 road하기
FileOutputStream os = new FileOutputStream("img.jpg"); //복사하기 C:\\java5\\File_Strame\\src에 저장됨
	int img =0; //읽는 바이트수
	int check =0; //읽는 횟수
	while((img=is.read(b))!=-1) { //이것도 가능 하고, true넣어서 (무한루프) 조건문으로 출력
				os.write(b); //반복문 사용하지 않음
				}

 

 

 

 

 

 

 

 

728x90

댓글