// Writes a string to the specified filename. If the filename doesn't exist, it is created. public static boolean writeToFile(String filename, String text, boolean appendToFile) throws IOException { BufferedWriter writer = null; try { File fileObject = new File(filename); // If file does not exist, create new file. if (!fileObject.exists()) { fileObject.createNewFile(); } if (fileObject.canWrite()) { writer = new BufferedWriter(new FileWriter(fileObject, appendToFile)); writer.write(text); writer.close(); return true; } } finally { // No matter the outcome, we need to make sure the // writer is closed if not properly closed before. if (writer != null) { try { writer.close(); } catch (Exception ex) { // Do Nothing } } } return false; }
Posted: March 20, 2023
Return to the snippets listing