java – 在磁盘上写入文件时锁定文件
发布时间:2020-12-15 05:15:19 所属栏目:Java 来源:网络整理
导读:我有两个独立的线程F1和F2(确切地说,两个 java.util.concurrent.FutureTask实例)并行运行. F1进行一些处理,然后将结果复制到XML文件中.然后,它重复这些步骤,直到它无关(创建了许多XML文件). F2查看F1输出目录,取一个文件,解析它,并对其执行一些处理. 这非常
我有两个独立的线程F1和F2(确切地说,两个
java.util.concurrent.FutureTask实例)并行运行.
F1进行一些处理,然后将结果复制到XML文件中.然后,它重复这些步骤,直到它无关(创建了许多XML文件). 这非常有效,除了有时F2从文件中获取截断的XML数据.我的意思是一个不完整的XML,其中一些XML节点不存在.问题是它并不总是可再现的,并且被截断的文件并不总是相同的. 我的问题:我想知道是否有一些机制锁定(甚至读取)文件F1当前正在写入,直到它完全完成将其写入磁盘,因此在文件解锁之前F2将无法读取它.或任何其他方式来解决我的问题将是受欢迎的! F1正在以这种方式编写文件: try { file = new File("some-file.xml"); FileUtils.writeStringToFile(file,xmlDataAsString); } catch (IOException ioe) { LOGGER.error("Error occurred while storing the XML in a file.",ioe); } F2正在以这种方式读取文件: private File getNextFileToMap() { File path = getPath(); // Returns the directory where F1 stores the results... File[] files = path.listFiles(new FilenameFilter() { public boolean accept(File file,String name) { return name.toLowerCase().endsWith(".xml"); } }); if (files.length > 0) { return files[0]; } return null; } // Somewhere in my main method of F2 ... f = getNextFileToMap(); Node xmlNode = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(f); if (doc != null) { xmlNode = doc.getDocumentElement(); } } catch (Exception e) { LOGGER.error("Error while getting the XML from the file " + f.getAbsolutePath(),e); } 解决方法
由于您已经在F2中过滤了.xml文件,因此将F1输出转换为.temp文件,然后将其重命名为.xml作为最后一步.这样,F2将忽略F1正在制作的文件,直到F1完全完成.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |