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));
}
다음 게시물에서는 바이트 배열을 파일로 저장하는 방법을 작성하려한다.
'Main > Java' 카테고리의 다른 글
[JAVA] 파일명 변경, 확장자 변경, 압축하기, 압축해제하기 (1) | 2020.09.02 |
---|---|
[JAVA] 커스텀 Exception 클래스 만들기 (0) | 2020.08.06 |
제어자 public, protected, private .. (0) | 2020.02.07 |
[JAVA] 오버로딩과 오버라이딩 (0) | 2020.01.16 |
[JAVA] 클래스변수 (Static 변수), static (0) | 2020.01.14 |