gpt4 book ai didi

java - 如何在 Android/Java 中同步 File 对象

转载 作者:行者123 更新时间:2023-12-02 10:32:03 26 4
gpt4 key购买 nike

我有两个Fragments和一个 File包含 JSON List<Competitor> 的表示。在第一Fragment我创建了一个 Competitor 。然后我发送这个Competitor通过 IntentService 到后台服务。在 IntentService如果打开File包含 List<Competitor> ,添加Competitor ,然后重新序列化/重写File

发送 Competitor 后到IntentService ,我将用户发送到下一个 Fragment (当后台服务正在写入文件时)。问题是下一个屏幕会查找相同的 File并尝试打开它,并将其解析为 List<Competitor>用于RecyclerView 。但是,如果后台服务仍在写入File ,我最终会得到 concurrentModificationException 。这并没有发生,因为 File写得很快,但我想防止这种可能性。

我想我可以synchronize关于File在两种不同的方法(写入和读取)中。我不知道这是否是正确的使用方式synchronize 。以下是我的想法:

写入方法

 public static void writeMasterCompetitorsFile(Context context, List<Competitor> competitors) {

File file = new File(context.getFilesDir(), MASTER_COMP_FILE);

synchronized (file) {
String jsonString = new Gson().toJson(competitors);

try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}

}

读取方法

公共(public)静态列表 getMasterCompetitorsList(Context context) {

List<Competitor> list = new ArrayList<>();
File file = new File(context.getFilesDir(), MASTER_COMP_FILE);

synchronized (file) {
if (file.exists()) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String compList = reader.readLine();
Type competitorListType = new TypeToken<List<Competitor>>() {
}.getType();
list = new Gson().fromJson(compList, competitorListType);
} catch (IOException e) {
e.printStackTrace();
}
} else {
writeMasterCompetitorsFile(context, list);
}
}

Android Studio告诉我我不应该synchronize在局部变量上。我的想法正确吗?

最佳答案

这是使用静态对象进行同步的示例。

public static final Object monitor = new Object();

public static void writeMasterCompetitorsFile(Context context, List<Competitor> competitors) {

File file = new File(context.getFilesDir(), MASTER_COMP_FILE);

synchronized (monitor) {
String jsonString = new Gson().toJson(competitors);

try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}

}

public static List getMasterCompetitorsList(Context context) {
List<Competitor> list = new ArrayList<>();
File file = new File(context.getFilesDir(), MASTER_COMP_FILE);

synchronized (monitor) {
if (file.exists()) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String compList = reader.readLine();
Type competitorListType = new TypeToken<List<Competitor>>() {
}.getType();
list = new Gson().fromJson(compList, competitorListType);
} catch (IOException e) {
e.printStackTrace();
}
} else {
writeMasterCompetitorsFile(context, list);
}
}
}

关于java - 如何在 Android/Java 中同步 File 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53562222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com