본문 바로가기
AI

Java로 데이터베이스에 저장된 파일 다운로드 및 실행하기

by 화풍 2023. 3. 1.
728x90
반응형

데이터베이스에 저장된 파일을 열기 위해서는 해당 파일을 먼저 로컬 컴퓨터에 다운로드해야 합니다. 다운로드한 후에는 앞서 언급한 방법과 마찬가지로 Desktop 클래스와 File 클래스를 사용하여 파일을 실행할 수 있습니다.

여기에는 몇 가지 예시가 있습니다.

  • JDBC를 사용하여 데이터베이스에서 파일 다운로드하기

import java.io.*; import java.sql.*; public class DownloadFileFromDatabase { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT file FROM mytable WHERE id = 1"); if (rs.next()) { Blob blob = rs.getBlob("file"); InputStream in = blob.getBinaryStream(); OutputStream out = new FileOutputStream("myfile.txt"); byte[] buffer = new byte[1024]; int length = -1; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); Desktop.getDesktop().open(new File("myfile.txt")); } rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }

이 예제는 JDBC를 사용하여 MySQL 데이터베이스에서 mytable 테이블의 id가 1인 레코드의 file 필드에 저장된 파일을 다운로드하고 실행하는 방법을 보여줍니다. 다운로드된 파일은 myfile.txt로 저장됩니다.

반응형
  • JPA를 사용하여 데이터베이스에서 파일 다운로드하기

import java.io.*; import javax.persistence.*; public class DownloadFileFromDatabase { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("mydatabase"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); MyEntity entity = em.find(MyEntity.class, 1); if (entity != null) { Blob blob = entity.getFile(); InputStream in = blob.getBinaryStream(); OutputStream out = new FileOutputStream("myfile.txt"); byte[] buffer = new byte[1024]; int length = -1; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); Desktop.getDesktop().open(new File("myfile.txt")); } tx.commit(); em.close(); emf.close(); } }

 

이 예제는 JPA를 사용하여 MyEntity 엔티티의 id가 1인 레코드의 file 필드에 저장된 파일을 다운로드하고 실행하는 방법을 보여줍니다. 다운로드된 파일은 myfile.txt로 저장됩니다. persistence.xml 파일에는 데이터베이스 연결 정보와 MyEntity 클래스와 매핑되는 정보가 포함되어 있어야 합니다.

728x90
반응형

댓글