728x90
Java.Io.InputStream을 File객체로 변환해서 파일 객체의 path 정보를 불러와야해서 새로 함수를 만들었다.
public File convertInputStreamToFile(InputStream inputStream) {
File tempFile = null;
try {
tempFile = File.createTempFile(String.valueOf(inputStream.hashCode()), ".tmp"); // 임시 파일 생성
tempFile.deleteOnExit();
copyInputStreamToFile(inputStream, tempFile);
} catch (Exception e) {
e.printStackTrace();
}
return tempFile;
}
먼저 임시파일을 만들어 copyInputStreamToFile에서 이 임시 객체를 가공해 반환한다.
public static void copyInputStreamToFile(InputStream inputStream, File file) {
try (FileOutputStream outputStream = new FileOutputStream(file)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (Exception e) {
e.printStackTrace();
}
}
https://soft.plusblog.co.kr/116
[Java] Inputstream 객체를 File 객체로 변환하기
InputStream 객체를 File 객체로 변환해야 할 경우가 있다. 예를 들어, 네트워크를 통해 읽은 데이터를 File 객체를 입력으로 받는 라이브러리에 사용하고 싶을 때 이런 변환이 필요하다. 우선 InputStrea
soft.plusblog.co.kr
1024 만큼의 버퍼를 두고 inputStream을 바이트 별로 읽어서 outputStream에 입력해준다.
이렇게 InputStream에 있는 정보들을 읽어 File 객체로 만들어줄 수 있다.

728x90
'Langauge > Java' 카테고리의 다른 글
Java의 정석 Chapter9. java.lang 패키지와 유용한 클래스 (0) | 2022.03.21 |
---|---|
Java의 정석 Chapter8. 예외처리(Exception Handling) (0) | 2022.03.21 |
Java의 정석 Chapter7.객체지향 프로그래밍2 (0) | 2022.03.13 |
Java의 정석 Chapter6. 객체지향 프로그래밍 (0) | 2022.03.13 |
Java의 정석 Chapter5. 배열 (0) | 2022.03.07 |