Spew the contents of a String object out to a file. As of 3.0 beta 2, this will replace and write \r\n for newlines on Windows. https://github.com/processing/processing/issues/3455 As of 3.3.7, this puts a newline at the end of the file, per good practice/POSIX: https://stackoverflow.com/a/729795
(String text, File file)
| 166 | * per good practice/POSIX: https://stackoverflow.com/a/729795 |
| 167 | */ |
| 168 | static public void saveFile(String text, File file) throws IOException { |
| 169 | String[] lines = text.split("\\r?\\n"); |
| 170 | File temp = File.createTempFile(file.getName(), null, file.getParentFile()); |
| 171 | try { |
| 172 | // fix from cjwant to prevent symlinks from being destroyed. |
| 173 | File canon = file.getCanonicalFile(); |
| 174 | // assign the var as second step since previous line may throw exception |
| 175 | file = canon; |
| 176 | } catch (IOException e) { |
| 177 | throw new IOException("Could not resolve canonical representation of " + |
| 178 | file.getAbsolutePath()); |
| 179 | } |
| 180 | // Could use saveStrings(), but the we wouldn't be able to checkError() |
| 181 | PrintWriter writer = PApplet.createWriter(temp); |
| 182 | for (String line : lines) { |
| 183 | writer.println(line); |
| 184 | } |
| 185 | boolean error = writer.checkError(); // calls flush() |
| 186 | writer.close(); // attempt to close regardless |
| 187 | if (error) { |
| 188 | throw new IOException("Error while trying to save " + file); |
| 189 | } |
| 190 | |
| 191 | // remove the old file before renaming the temp file |
| 192 | if (file.exists()) { |
| 193 | boolean result = file.delete(); |
| 194 | if (!result) { |
| 195 | throw new IOException("Could not remove old version of " + |
| 196 | file.getAbsolutePath()); |
| 197 | } |
| 198 | } |
| 199 | boolean result = temp.renameTo(file); |
| 200 | if (!result) { |
| 201 | throw new IOException("Could not replace " + file.getAbsolutePath() + |
| 202 | " with " + temp.getAbsolutePath()); |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | |
| 207 | /** |
no test coverage detected