android - Read and Write to file in the same time -
i want write , read file in same time without errors. example, starting new thread writing file running service. in activity starting new thread reading same file. wan't synchronously. thing :
- to wait execution of next thread until previous finished.
- next thread must not start until previous thread stops, irrespective of time consumption.
my code read , write:
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(); }
thanks in advance.
if want read method called thread wait write method called thread finished, , vice versa, synchronize both methods on common object:
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] } }
Comments
Post a Comment