Java

Java - InputStream 을 byte 배열로 변환

구티맨 2022. 1. 19. 15:11

목차

    1. readAllBytes()

    inputstream의 readAllBytes()는 JAVA9 버전부터 이용이 가능합니다.

    package com.example.logbacksample;
    
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.io.IOUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.core.io.ResourceLoader;
    import org.springframework.stereotype.Component;
    
    import java.io.InputStream;
    
    @Slf4j
    @Component
    public class ResourceApplicationRunner implements ApplicationRunner {
        @Autowired
        ResourceLoader resourceLoader;
    
        @Override
        public void run(ApplicationArguments args) throws Exception {
            InputStream inputStream = resourceLoader.getResource("classpath:res.txt").getInputStream();
            byte[] bytes = inputStream.readAllBytes();
            log.info("bytes : " + new String(bytes));
            inputStream.close();
        }
    }

    2. toByteArray()

    package com.example.logbacksample;
    
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.io.IOUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.core.io.ResourceLoader;
    import org.springframework.stereotype.Component;
    
    import java.io.InputStream;
    
    @Slf4j
    @Component
    public class ResourceApplicationRunner implements ApplicationRunner {
        @Autowired
        ResourceLoader resourceLoader;
    
        @Override
        public void run(ApplicationArguments args) throws Exception {
            InputStream inputStream = resourceLoader.getResource("classpath:res.txt").getInputStream();
            byte[] byteArray = IOUtils.toByteArray(inputStream);
            log.info("byteArray : " + new String(bytes));
            inputStream.close();
        }
    }