Java读写XML数据文件时出现“Premature end of file”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/708327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:35:42  来源:igfitidea点击:

"Premature end of file" error when Java read and writes XML data files

javaxmlservlets

提问by shuby_rocks

I have been using JDOM library to read and write XML files through Java Servlets.

我一直在使用 JDOM 库通过 Java Servlets 来读写 XML 文件。

Problem is that when I send many requests using AJAX to my servlets which read and write data in XML files, many times it fails displaying error: Premature end of file. How can I synchronize all these read/writes to files or is there any other way to prevent these problem? Let me know if more details are required.

问题是,当我使用 AJAX 向在 XML 文件中读取和写入数据的 servlet 发送许多请求时,很多时候它都无法显示错误:文件过早结束。如何将所有这些读/写同步到文件,或者有没有其他方法可以防止这些问题?如果需要更多详细信息,请告诉我。

Will use of threads do any good in this situation?

在这种情况下,使用线程会有什么好处吗?

Thanks a lot!

非常感谢!

采纳答案by Ry4an Brase

Two possible solutions are:

两种可能的解决方案是:

  • Write your files to thename.xml.part and then once done/closed to a rename to thename.xml, which makes the write closer to being atomic -- the reader can't read it until it's surely done so long as it is looking for ".xml" files only.
  • or, use a Database, atomicity is what they do.
  • 将您的文件写入 thename.xml.part,然后在完成/关闭后重命名为 thename.xml,这使得写入更接近于原子性——读者无法读取它,直到它确定完成,只要它在看仅适用于“.xml”文件。
  • 或者,使用数据库,原子性就是他们所做的。

回答by Shaiful Islam

I have faced such type of problem but exactly not the same. I am sharing my experience about this error. Please, sorry for any inconvenience.

我遇到过这种类型的问题,但完全不一样。我正在分享我对这个错误的经验。如有不便,敬请谅解。

I have faced the following problem

我遇到了以下问题

  1. I have to form a xml file with dynamic variable data. And post that xml to a URL by PostMethod in java.

  2. Normally It works. But when dynamic variable data is null. Then it shows the “Premature end of file".

  1. 我必须用动态变量数据形成一个xml文件。并通过 java 中的 PostMethod 将该 xml 发布到 URL。

  2. 通常它有效。但是当动态变量数据为空时。然后它显示“文件过早结束”。

Solution:

解决方案:

  1. Just checking the variable is null or not. And it works for me.
  1. 只是检查变量是否为空。它对我有用。

回答by Bilal Mustafa

I have also faced this problem. My experience is...

我也遇到过这个问题。我的经验是...

  1. Clean Project
  2. Rebuild Project
  1. 清洁工程
  2. 重建项目

then it will run successfully....

然后它会成功运行......

回答by HimanshuKalra

Try adding all the write requests to a Process Queueand then build/append XML by those elements of Queue.

尝试将所有写入请求添加到进程队列,然后通过队列的这些元素构建/附加 XML。