Created
September 7, 2018 20:36
-
-
Save oddmario/e1430a4e776a9e53bc01f9d75b77bf41 to your computer and use it in GitHub Desktop.
Thread safe writer for Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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