Skip to content

Instantly share code, notes, and snippets.

@oddmario
Created September 7, 2018 20:36
Show Gist options
  • Save oddmario/e1430a4e776a9e53bc01f9d75b77bf41 to your computer and use it in GitHub Desktop.
Save oddmario/e1430a4e776a9e53bc01f9d75b77bf41 to your computer and use it in GitHub Desktop.
Thread safe writer for Java
public static void ThreadsafeWriter(String text, String file) throws IOException {
/*
@author: mariolatiffathy
@source: gist.github
@description: A thread-safe writer that you can use to write to the same file through multiple threads.
@usage: ThreadsafeWriter(String: text, String: file)
@example: ThreadsafeWriter("Hello World", "File.txt")
@methodType: public, static
*/
String nodeValue = text;
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
synchronized (writer) {
String[] words = nodeValue.split(" ");
for (String word: words) {
writer.write(word);
writer.newLine();
}
writer.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment