gpt4 book ai didi

android - 同时读取和写入文件

转载 作者:搜寻专家 更新时间:2023-11-01 07:53:39 24 4
gpt4 key购买 nike

我想同时写入和读取文件而不会出错。例如,我将启动新线程以从我正在运行的服务写入文件。在我的 Activity 中,我将启动新线程以从同一个文件中读取。我不想同步执行此操作。像这样的事情:

  1. 等待下一个线程的执行直到上一个线程完成。
  2. 下一个线程必须等到前一个线程停止后才开始,无论耗时如何。

我的读写代码:

public static final String ROUTE_FILE_NAME = "route.txt";

public static void savePointToFile(Context context, String point) throws IOException {

FileOutputStream fOut = context.openFileOutput(ROUTE_FILE_NAME, Context.MODE_APPEND);

OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(point);
osw.flush();
osw.close();
}

public static String readRouteFromFile(Context context) {
StringBuffer fileContent = new StringBuffer(UIUtils.emptyString());
byte[] buffer = new byte[1024];
try {
FileInputStream fis = context.openFileInput(ROUTE_FILE_NAME);

int length;

while ((length = fis.read(buffer)) != -1) {
fileContent.append(new String(buffer));
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileContent.toString();
}

提前致谢。

最佳答案

如果您只想让从一个线程调用的读取方法等待从另一个线程调用的写入方法完成,反之亦然,只需在一个公共(public)对象上同步这两个方法:

private static final Object fileLock = new Object();

public static String readFile() {
synchronize(fileLock) {
[your current read code here]
}
}

public static void write(String data) {
synchronize(fileLock) {
[your current write code here]
}
}

关于android - 同时读取和写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31278430/

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