본문 바로가기

Java

[Stream] InputStream, OutputStream

스트림에 대한 공부를 하면서 몇가지 정리를 하고자...
FileInputStream과 FileOutputStream을 통해서 이미지 파일을 카피 해보자..
File f = new File(image);
  int fileSize = (int)f.length();
  
  byte[]b = new byte[fileSize];
  int pos = 0;
  int size = 10;
  int temp; 

  FileInputStream fis = new FileInputStream(image);
  FileOutputStream fos = new FileOutputStream("d:/copy.jpg");
  
  int i = -1;
  
  while((i=fis.read()) != -1) {
   System.out.println((char)i);
   fos.write(i);
  }
  fis.close();
  fos.close();
  
 }

위 코드처럼 jpg 파일을 바이트로 읽어와서 바로 FileOutputStream을 통해서 write 하면
jpg 파일을 그대로 copy 할 수 있다.
 
  byte[]b1 =new byte[fileSize];
  while((size = fis.read(b1)) > 0) {

  }

이런식으로 가져와서 나중에
fos.write(b1);
이렇게 해도 결과는 같다.