如何在写入文件时在同一个线程中等待完成,以便我们可以使用它

时间:2014-12-02 09:21:54

标签: java android

我有一个文件打开和写入情况,在大约20到30次时会因EOFException崩溃一次,因为该文件不可用,因为其他进程正在写入它。

我可以捕获这个异常,然后以某种方式等待文件写操作同步结束,所以我可以递归方法吗?

File productJSON = getFileStreamPath("product" + "_" + getId() + ".json");
if (!productJSON.exists()) {
    productJSON = getFileStreamPath("product" + ".json");
}

InputStream jsonStringsFileInputStream;
try {
    jsonStringsFileInputStream = new FileInputStream(productJSON);

    HashMap<String, Map> that = new JSONToProductParser().convertThisToThat(jsonStringsFileInputStream);

} catch (FileNotFoundException e) {
    e.printStackTrace();
}

2 个答案:

答案 0 :(得分:1)

您可以在打开文件之前检查文件的写入权限。这是通过 canWrite()方法完成的。

Oracle Docs - File # canWrite

同时查看这个已解决的问题。它处理synchronized属性。

Solved Question - Synchronized

答案 1 :(得分:-1)

您可以使用处理程序在代码中引入延迟。

final Handler handler=new Handler();
handler.postdelayed(new Runnable(){
@override
public void run(){
//Do something after 5 seconds....your code here
     }
},5000);

在run方法中编写代码

相关问题