CORE
HOME > JAVA > J2SE > CORE
2019.01.13 / 22:25

[JAVA]ByteArray를 사용한 파일 읽기 쓰기

hanulbit
추천 수 91

이전에는 FileInputStream과 FileOutputStream을 사용한 파일 읽기/쓰기/삭제 예제를 포스팅했었는데. 이번에는

ByteArrayInputStream와 ByteArrayOutputStream을 이용한 파일 읽기/쓰기 샘플 코드를 올린다. 

 

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

 

public class FileReadWriteByByteArray {

     public static void main(String[] arg){
     
         String origFilePath = "C:/egov_dev/workspace/JavaSample/testdata/file";
         String origFileNm = "나무사진.jpg"; 
         String newFilePath = "C:/egov_dev/workspace/JavaSample/testdata/file/back";
         String newFileNm = "사진2.JPG";  

         FileInputStream fin = null;
         ByteArrayOutputStream bao = null;
         FileOutputStream fos = null;
         BufferedOutputStream bos = null;
         ByteArrayInputStream bin = null;
  
         try {
             //파일 읽기 기능
            int bytesRead = 0;
            byte[] buff = new byte[1024];
            String fullPah = origFilePath + "/" + origFileNm;
   
            File file = new File(fullPah);
            fin = new FileInputStream(file);
            bao = new ByteArrayOutputStream();
            while((bytesRead = fin.read(buff)) > 0) {
                   bao.write(buff, 0, bytesRead);
            }
            byte[] fileByte = bao.toByteArray(); 

 

            // 파일 쓰기 기능
            int readCount = 0;
            bin = new ByteArrayInputStream( fileByte );
            fos = new FileOutputStream( newFilePath + "/" + newFileNm );
            bos = new BufferedOutputStream( fos );
            byte[] outBuffer = new byte[65536];
            while( (readCount = bin.read(outBuffer)) > 0 ){
                 bos.write(outBuffer, 0, readCount);
            }
       
       } catch (FileNotFoundException e) {
           //e.printStackTrace();
           System.out.println(e.getMessage());
       } catch (IOException e) {
           //e.printStackTrace();
           System.out.println(e.getMessage());
      }finally{
           try {fin.close();} catch (IOException e) {e.printStackTrace();}
           try {bao.close();} catch (IOException e) {e.printStackTrace();}
           try {fos.close();} catch (IOException e) {e.printStackTrace();}
           try {bos.close();} catch (IOException e) {e.printStackTrace();}
           try {bin.close();} catch (IOException e) {e.printStackTrace();}
           System.out.println("완료!");
     }
 }
}