gpt4 book ai didi

java - 服务中存储类的同步和/或互斥

转载 作者:行者123 更新时间:2023-12-01 17:17:04 25 4
gpt4 key购买 nike

我需要在我的应用程序中同时读取和写入具有不同 jobIntentServices 的公共(public)文件。一个服务(生产者)将数据写入文件中,而另一个服务(消费者)检查共享文件中是否有数据。如果有数据,则发送该数据;如果数据传输成功,则删除该文件。我创建了以下存储 Controller 类:

public class Storage {
private static final String TAG = "Storage";

public void writeToFile(String filePath, String data, Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filePath, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}

public String readFromFile(String filePath, Context context) {

String ret = "";

try {
InputStream inputStream = context.openFileInput(filePath);

if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();

while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append("\n").append(receiveString);
}

inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}

return ret;
}

public boolean fileExists(String filename, Context context) {
File file = context.getFileStreamPath(filename);
if(file == null || !file.exists()) {
return false;
}
return true;
}

public boolean deleteFile(String filename, Context context){
File file = context.getFileStreamPath(filename);
return file.delete();
}

该类不是单例。

最佳答案

我用单例类并使用锁解决了这个问题:

Lock lockDeviceData = new ReentrantLock();

关于java - 服务中存储类的同步和/或互斥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61363817/

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