File Format Check

Hi ,
I have written the following code for checking format of a file

Document doc1 = new Document("FilePath");

ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// Save the document to stream.
doc1.save(outStream, SaveFormat.DOCX);

// Convert the documentStream 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);
Document doc = new Document(inStream);
FileFormatInfo info = FileFormatUtil.detectFileFormat(inStream);
System.out.println(info.getLoadFormat());
System.out.println(FileFormatUtil.loadFormatToExtension(info.getLoadFormat()));

But I am getting the following exception

255Exception in thread “main”
java.lang.IllegalArgumentException: Cannot convert this load format to a file extension.
at com.aspose.words.FileFormatUtil.loadFormatToExtension(Unknown Source)

Plz Help

Regards,
Rajesh

Hi Rajesh,

Thanks for your inquiry. Please reset the InputStream as highlighted in following code example to get the required output.

Please let us know if you have any more queries.

Document doc1 = new Document(MyDir + "Input.docx");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// Save the document to stream.
doc1.save(outStream, SaveFormat.DOCX);
// Convert the documentStream 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);
Document doc = new Document(inStream);
inStream.reset();
FileFormatInfo info = FileFormatUtil.detectFileFormat(inStream);
System.out.println(info.getLoadFormat());
System.out.println(FileFormatUtil.loadFormatToExtension(info.getLoadFormat()));