This is an example for testing our error; our source and destiny file is the same.
The method “Document.save(…)” throws a RANDOM “java.io.FileNotFoundException (Access Denied)” and the file is deleted!!! Why? How can I control that? How can I know when the file is liberated?
Thanks for your inquiry. You are loading and saving the docx with same name 100000 times. Could you please share some detail about your Use Case? Perhaps, there is some other way to achieve your requirements.
That code is only an illustrative and summarized example about my issue…
We have a complex Web application running on a Tomcat server. The summary about our use case with Aspose.Words is: Our application loads a Word document (.doc or .docx) in a “Document” object, it’s processed (some text marks are replaced) and then the document is saved in the same file. After that, our web application continues its execution and processes the modified file.
The problem is that the “Document.save()” method throws randomly an “java.io.FileNotFoundException (Access Denied)”. At that time, the file is strangely deleted.
This happens randomly, so I’ve coded a “do…while” loop with many iterations to show you an illustrative example. That way, I force the realization of a high number of executions to generate the error, that loop does not exist in our real case. Not really necessary to call to “Document.save()” many times, the error can occur with ONE single execution… But I repeat, it’s a random exception (but it’s quite common).
My personal impression is that the “Document.save()” method doesn’t always work right, doing something strange. It blocks the document for indefinite time while saving the document and this blockade sometimes generates the exception. I don’t understand why this method eliminates my Word file when that happens! The file should be maintained without deleting.
I hope that my sample code can help you to replicate this error and get an explanation and a possible solution. Please, you can run the source code yourself and check that effectively that happens.
It’s an urgent problem for a major project, I appreciate your help very much.
Thanks for sharing the detail. You are saving the same document with same modification 100000 times, this seems not to be a real scenario. It would be great if you please share your original Use Case here for our reference. We will then provide you more information about your query.
The shared code does not throws exception every time. This code example successfully executed some times. See the attached image for detail. It would be great if you please share your original Use Case. We will then investigate the issue and log it in our issue tracking system if it is a bug. Thanks for your cooperation.
I don’t understand very well. You say: “This code example successfully executed some times”. Sometimes or always? Did you manage to reproduce the exception?
This is the source code for our complex real case, I hope this excerpt is enough. (The main method is: public static Boolean contieneMarcasConPrefijo(…)).
MsWordUtil.java
/** Determina si un documento de Word contiene o no marcas que comiencen
* con el prefijo indicado con el formato señalado.
*
* @param rutaFichero Ruta al fichero de Word.
* @param prefijo Prefijo de la marca.
* @param colorMarcas Color que deben tenre las marcas buscadas. Por ejemplo: Color.RED
* @param sonMarcasOcultas Visibilidad de las marcas buscadas. Por ejemplo: Boolean.TRUE
* @return Resultado de la búsqueda.
* @throws Exception
*/
public static Boolean contieneMarcasConPrefijo(String rutaFichero, String prefijo, Color colorMarcas, Boolean sonMarcasOcultas) throws Exception {
boolean resultado = false;
if (rutaFichero != null && prefijo!=null && colorMarcas != null && sonMarcasOcultas != null) {
String ext = FilenameUtils.getExtension(rutaFichero);
// Si la extensión del fichero es "doc" o "docx" se examina el documento.
if ("doc".equalsIgnoreCase(ext) || "docx".equalsIgnoreCase(ext)) {
// Se crea un analizador de destino a partir de la ruta del fichero Word para marcas en el formato indicado.
AnalizadorWord analizadorWord = new AnalizadorWord(rutaFichero, colorMarcas, sonMarcasOcultas, null, null, null, null, null);
// El analizador de destino fusiona los nodos Run de igual formato en el documento de Word.
try {
analizadorWord.fusionarNodosIgualFormato();
}
catch (Exception e) {
e.printStackTrace();
logger.error("No se han podido fusionar los nodos Run de igual formato antes de examinar el documento " + rutaFichero);
}
// El analizador carga la lista de marcas del documento Word.
analizadorWord.cargarMarcas();
// Análisis de la lista de marcas.
ArrayList listaMarcas = analizadorWord.getListaMarcas();
if (listaMarcas!=null && listaMarcas.size()>0) {
// Se recorren todas las marcas de la lista de marcas comprobando si contienen el prefijo.
Iterator iterator = listaMarcas.iterator();
while (iterator.hasNext()) {
String marca = (String) iterator.next();
if (marca.trim().startsWith(prefijo)) return true;
}
}
}
}
return resultado;
}
/**
* Guarda un documento de Word en la ruta especificada, grabando a vacío sus
* principales metadatos.
*
* @param doc Documento de Word.
* @param rutaFichero ruta al fichero.
* @throws Exception
*/
public static void salvarDocumento(Document doc, String rutaFichero) throws Exception {
doc.getBuiltInDocumentProperties().setAuthor("");
doc.getBuiltInDocumentProperties().setComments("");
doc.getBuiltInDocumentProperties().setCompany("");
doc.getBuiltInDocumentProperties().setKeywords("");
doc.getBuiltInDocumentProperties().setTitle("");
doc.getBuiltInDocumentProperties().setLastSavedBy("");
doc.getBuiltInDocumentProperties().setCategory("");
doc.getBuiltInDocumentProperties().setContentStatus("");
doc.getBuiltInDocumentProperties().setManager("");
doc.getBuiltInDocumentProperties().setNameOfApplication("");
doc.getBuiltInDocumentProperties().setSubject("");
doc.getBuiltInDocumentProperties().setTemplate("");
doc.getBuiltInDocumentProperties().setContentType("");
FileFormatInfo info = FileFormatUtil.detectFileFormat(rutaFichero);
doc.save(rutaFichero, info.getLoadFormat());
}
AnalizadorWord.java
...
...
...
/**
* Fusiona todos los nodos Run consecutivos de igual formato del documento
* de Word.
*
* Este método modifica el fichero.
*
* @throws Exception
*/
public void fusionarNodosIgualFormato() throws Exception {
try {
// Se abre el documento.
Document doc = new Document(rutaFichero);
// Fusión de nodos Run consecutivos con el mismo formato.
doc.joinRunsWithSameFormatting();
// Se guarda el documento con las modificaciones.
MsWordUtil.salvarDocumento(doc, this.getRutaFichero());
} catch (Exception e) {
e.printStackTrace();
logger.error("Error fusionando nodos Run consecutivos de igual formato del documento");
throw e;
}
}
Thanks for sharing the detail. In your case, we suggest you please check the file size and check either it exists or not before loading it into Aspose.Words DOM.
Please check following code snippet for your kind reference. Hope this helps you.
File file = new File(path);
if (file.exists() && file.length() > 0)
{
Document doc = new Document(path);
doc.joinRunsWithSameFormatting();
System.out.println("Runs joined...");
saveDocumentNow(doc, path);
System.out.println("Saved...");
}
Thanks for your patience. It is to inform you that our product team has completed the work on this issue (WORDSNET-12716) and has come to a conclusion that this issue and the undesired behavior you’re observing is actually not a bug in Aspose.Words. So, we have closed this issue as ‘Not a Bug’.
It is expected behavior, it is just not enough time for the process to release the document object.
You are importing and exporting the same file at same place 100000 times. There is not enough time for the process to release the Aspose.Words.Document object. So the exception is thrown. If you save the document with different output file names e.g 100000 times, you will not get any exception.
That could be a solution for the example but it is not a valid solution for our real case. We are having serious problems with this issue in our real case, we’re really desperate …
The real problem is that it is not enough time for the process to release the document object. That time is variable and unpredictable, but we need to treat the file immediately after running the save() method.
I thought about applying a Thread.sleep(…) after the Document.save() statement but we don’t know the number of milliseconds it will take to release the object. In addition, the user of application cannot wait too long.
Thanks for your inquiry. Please note that according to shared code example It is expected behavior. This is not an issue.
In case you are using an older version of Aspose.Words, we would suggest you please upgrade to the latest version (v15.10.0) from here and let us know how it goes on your side.
If the problem still remains, please share some more detail about your Use Case along with following detail. Perhaps, there is another way to achieve your requirements.
Are you loading and saving document 100000 times for testing purpose?
Unfortunately, we do not understand the scenario. Please share why you are loading/saving document 100000 times without any change in a loop.
Please share detail about your real time scenario e.g your system is getting input document from user and after modifying the document, system downloads the document at user’s end.
Thanks for your inquiry. Please note that according to shared code example It is expected behavior. This is not an issue.
In case you are using an older version of Aspose.Words, we would suggest you please upgrade to the latest version (v15.10.0) from here and let us know how it goes on your side.
- Error continues with the latest version (v15.10.0) too.
If the problem still remains, please share some more detail about your Use Case along with following detail. Perhaps, there is another way to achieve your requirements.
Are you loading and saving document 100000 times for testing purpose.
- That does not happen in our real case: THERE IS NOT A LOOP.
Unfortunately, we do not understand the scenario. Please share why you are loading/saving document 100000 times without any change in a loop.
- THERE IS NOT A LOOP, that is only an example.
Please share detail about your real time scenario e.g your system is getting input document from user and after modifying the document, system downloads the document at user’s end.
**- Real time scenario:
Our web application generates the Ms Word document.
User modifies the document (.doc or .docx).
User uploads the document again to our application.
Our application joins “Run” nodes with the same format.
Our application replaces some text marks (texts in red) in the document.
Our application saves to same file again (.doc or .docx).
Our application compresses the file in a .zip file.
The .zip file is stored in our system.** The error is happening in point 6).
Our web application generates the Ms Word document.
User modifies the document (.doc or .docx).
User uploads the document again to our application.
Our application joins “Run” nodes with the same format.
Our application replaces some text marks (texts in red) in the document.
Our application saves to same file again (.doc or .docx).
Our application compresses the file in a .zip file.
The .zip file is stored in our system.
The error is happening in point 6).*
Thanks for sharing the real time scenario. This scenario differ from the code example (loop 100000 times) shared in your first post. The document is uploaded, loaded into Aspose.Word DOM and saved with same file name by your web application. We suggest you following points. Hope this helps you.
Please make sure that the file is uploaded by the web application correctly. You can either the document exists or not before loading it into Aspose.Words DOM.
Please remove the existing document when user uploads modified document.
If you still face problem, please share following detail for investigation purposes.
Please attach your input Word document which you are using in your real time scenario.
Please share the exact exception detail (stack trace)
Please create a standalone Java application (source code without compilation errors) that helps us reproduce your problem on our end and attach it here for testing.
As soon as you get these pieces of information to us we’ll start our investigation into your issue.
The error occurs randomly even if it’s the same document, at present I have no stack trace. It’s a dead end, I’ll leave it here for now. I will ask again in the forum when I have more information. Thank you anyway.
Sets consent for sending user data to Google for online advertising purposes.
Sets consent for personalized advertising.
Cookie Notice
To provide you with the best experience, we use cookies for personalization, analytics, and ads. By using our site, you agree to our cookie policy.
More info
Enables storage, such as cookies, related to analytics.
Enables storage, such as cookies, related to advertising.
Sets consent for sending user data to Google for online advertising purposes.
Sets consent for personalized advertising.
Cookie Notice
To provide you with the best experience, we use cookies for personalization, analytics, and ads. By using our site, you agree to our cookie policy.
More info
Enables storage, such as cookies, related to analytics.
Enables storage, such as cookies, related to advertising.
Sets consent for sending user data to Google for online advertising purposes.