데이터베이스의 문서 직렬화 및 작업

문서 작업을 수행할 때 수행해야 할 작업 중 하나는 데이터베이스에서Document개체를 저장하고 검색하는 것입니다. 예를 들어 모든 유형의 콘텐츠 관리 시스템을 구현하는 경우 이 작업이 필요합니다. 모든 이전 버전의 문서는 데이터베이스 시스템에 저장되어야 합니다. 데이터베이스에 문서를 저장하는 기능은 응용 프로그램이 웹 기반 서비스를 제공하는 경우에도 매우 유용합니다.

Aspose.Words데이터베이스에서 이 문서를 사용한 후속 작업을 위해 문서를 바이트 배열로 변환하는 기능을 제공합니다.

문서를 바이트 배열로 변환

문서를 데이터베이스에 저장하거나 웹을 통해 전송하기 위해 문서를 준비하려면 종종 바이트 배열을 얻기 위해 문서를 직렬화해야합니다.

Aspose.Words에서Document개체를 직렬화하려면:

  1. Document클래스의Save메서드 오버로드를 사용하여MemoryStream에 저장합니다.
  2. 바이트 형태로 문서를 나타내는 바이트 배열을 반환하는ToArray메서드를 호출합니다.

위의 단계는 바이트를Document객체로 다시 로드하기 위해 되돌릴 수 있습니다.

아래 예제에서는Document개체를 직렬화하여 바이트 배열을 얻은 다음 바이트 배열을 직렬화하여Document개체를 다시 얻는 방법을 보여 줍니다:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Load the document.
Document doc = new Document(dataDir + "Test File (doc).doc");
// Create a new memory stream.
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// Save the document to stream.
doc.save(outStream, SaveFormat.DOCX);
// Convert the document to byte form.
byte[] docBytes = outStream.toByteArray();
// The bytes are now ready to be stored/transmitted.
// Now reverse the steps to load the bytes back into a document object.
ByteArrayInputStream inStream = new ByteArrayInputStream(docBytes);
// Load the stream into a new document object.
Document loadDoc = new Document(inStream);

데이터베이스에 문서 저장,읽기 및 삭제

이 섹션에서는 문서를 데이터베이스에 저장한 다음Document개체로 다시 로드하여 작업하는 방법을 보여 줍니다. 단순화를 위해 파일 이름은 데이터베이스에서 문서를 저장하고 가져오는 데 사용되는 키입니다. 데이터베이스에는 두 개의 열이 있습니다. 첫 번째 열"FileName"는 문자열로 저장되며 문서를 식별하는 데 사용됩니다. 두 번째 열"FileContent"은 바이트 형태로 문서 객체를 저장하는BLOB객체로 저장됩니다.

다음 코드 예제에서는 데이터베이스에 대한 연결을 설정하고 명령을 실행하는 방법을 보여 줍니다:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String url1 = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123";
// Open a database connection.
Connection mConnection = DriverManager.getConnection(url1, user, password);

다음 코드 예제에서는 문서를 데이터베이스에 저장한 다음 동일한 문서를 다시 읽고 마지막으로 해당 문서가 포함된 레코드를 데이터베이스에서 삭제하는 방법을 보여 줍니다:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Store the document to the database.
StoreToDatabase(doc, mConnection);
// Read the document from the database and store the file to disk.
Document dbDoc = ReadFromDatabase(dataDir + fileName, mConnection);
// Save the retrieved document to disk.
dbDoc.save(dataDir + fileName);
// Delete the document from the database.
DeleteFromDatabase(dataDir + fileName, mConnection);
// Close the connection to the database.
mConnection.close();

데이터베이스에 문서 저장

데이터베이스에 문서를 저장하려면 이 문서의 시작 부분에 설명된 대로 이 문서를 바이트 배열로 변환합니다. 그런 다음 이 바이트 배열을 데이터베이스 필드에 저장합니다.

다음 코드 예제에서는 지정된 데이터베이스에 문서를 저장하는 방법을 보여 줍니다:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void StoreToDatabase(Document doc, Connection mConnection) throws Exception {
// Create an output stream which uses byte array to save data
ByteArrayOutputStream aout = new ByteArrayOutputStream();
// Save the document to byte array
doc.save(aout, SaveFormat.DOCX);
// Get the byte array from output steam
// the byte array now contains the document
byte[] buffer = aout.toByteArray();
// Get the filename from the document.
String fileName = doc.getOriginalFileName();
String filePath = fileName.replace("\\", "\\\\");
// Create the SQL command.
String commandString = "INSERT INTO Documents (FileName, FileContent) VALUES('" + filePath + "', '" + buffer
+ "')";
Statement statement = mConnection.createStatement();
statement.executeUpdate(commandString);
}

모든 작업을 수행하는SQL식인commandString을 지정합니다:

  • 문서를 데이터베이스에 저장하려면"INSERTINTO"명령이 사용되며 두 개의 레코드 필드(FileName및FileContent)의 값과 함께 테이블이 지정됩니다. 추가 매개 변수를 피하기 위해 파일 이름은Document개체 자체에서 가져옵니다. FileContent필드 값은 저장된 문서의 이진 표현을 포함하는 메모리 스트림에서 바이트가 할당됩니다.
  • 나머지 코드 줄은Aspose.Words문서를 데이터베이스에 저장하는 명령을 실행합니다.

데이터베이스에서 문서 검색

데이터베이스에서 문서를 검색하려면 문서 데이터를 바이트 배열로 포함하는 레코드를 선택합니다. 그런 다음 레코드의 바이트 배열을MemoryStream로 로드하고MemoryStream에서 문서를 로드할Document개체를 만듭니다.

다음 코드 예제에서는 파일 이름을 키로 사용하여 이 문서를 가져오는 지정된 데이터베이스에서 문서를 검색하고 반환하는 방법을 보여 줍니다:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static Document ReadFromDatabase(String fileName, Connection mConnection) throws Exception {
// Create the SQL command.
String commandString = "SELECT * FROM Documents WHERE FileName=?";
PreparedStatement statement = mConnection.prepareStatement(commandString);
statement.setString(1, fileName);
Document doc = null;
ResultSet result = statement.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("FileContent");
InputStream inputStream = blob.getBinaryStream();
doc = new Document(inputStream);
inputStream.close();
System.out.println("File saved");
}
result.close();
return doc;
}

데이터베이스에서 문서 삭제

데이터베이스에서 문서를 삭제하려면Document개체에 대한 조작 없이 적절한SQL명령을 사용합니다.

다음 코드 예제에서는 파일 이름을 사용하여 레코드를 가져오는 데이터베이스에서 문서를 삭제하는 방법을 보여 줍니다:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static void DeleteFromDatabase(String fileName, Connection mConnection) throws Exception {
// Create the SQL command.
String commandString = "DELETE FROM Documents WHERE FileName='" + fileName + "'";
Statement statement = mConnection.createStatement();
// Delete the record.
statement.execute(commandString);
}