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

[JAVA]ByteArray¸¦ »ç¿ëÇÑ ÆÄÀÏ Àб⠾²±â

hanulbit
Ãßõ ¼ö 255

ÀÌÀü¿¡´Â 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("¿Ï·á!");
     }
 }
}