5 ~ 6개월만에 포스팅을 한다. 공부하면서 포스팅까지 하기에는 내 게으른 영혼이 허락하지 않는가부다 ㅎㅎㅎㅎㅎㅎㅎㅎ 몇몇 개발자 블로그에서 본 글귀들이 이 보잘것 없는 나의 티스토리를 다시 떠오르게 했다. (기억보단 기록을, 기록은 기억을 이긴다 등)

파일을 바이트 배열로 변환 하는 방법 2가지

순수 자바 이용 방법

public void test1 () {

  File f = new File("파일 경로");
  byte[] file = new byte[(int) f.length()];

  try (
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis)
  ) {
    dis.readFully(file);
  } catch (IOException e) {
    e.printStackTrace();
  }

  assertNotNull(file);

  System.out.println("byte[] length by Vanilla Java: " + file.length);
  System.out.println("Content : " + new String(file));
}

Guava 라이브러리 이용 방법

  public void test2 () {

    File f = new File("파일 경로");
    byte[] file = null;

    try (FileInputStream is = new FileInputStream(f)) {
      file = ByteStreams.toByteArray(is);
    } catch (IOException e) {
      e.printStackTrace();
    }

    assertNotNull(file);

    System.out.println("byte[] length by Guava: " + file.length);
    System.out.println("Content : " + new String(file));
  }

다음 게시물에서는 바이트 배열을 파일로 저장하는 방법을 작성하려한다.

+ Recent posts