티스토리 뷰

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();
        }
    }

    'Java' 카테고리의 다른 글

    Java annotation(2) - Custom Annotation  (0) 2022.04.01
    Mac m1 openjdk 설치  (0) 2022.02.17
    Java List 생성 방법  (0) 2021.10.01
    Java 제네릭(generic) 이란  (0) 2021.05.11
    JAVA 버전에 대하여..( JAVA 1.8 JAVA 8 ... )  (0) 2021.01.18
    댓글
    공지사항
    최근에 올라온 글
    최근에 달린 댓글
    Total
    Today
    Yesterday
    링크
    «   2024/11   »
    1 2
    3 4 5 6 7 8 9
    10 11 12 13 14 15 16
    17 18 19 20 21 22 23
    24 25 26 27 28 29 30
    글 보관함