/** writes safely (to temp file, then rename) */ static void saveTextFileWithEncoding(String fileName, String contents, S encoding) throws IOException { CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)"); try { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; File tempFile = new File(tempFileName); if (contents != null) { if (tempFile.exists()) try { S saveName = tempFileName + ".saved." + now(); copyFile(tempFile, new File(saveName)); } catch (Throwable e) { printStackTrace(e); } FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, encoding); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (contents != null) if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); } finally { action.done(); } } static void saveTextFileWithEncoding(File fileName, String contents, S encoding) ctex { saveTextFileWithEncoding(fileName.getPath(), contents, encoding); }
Began life as a copy of #1001042
download show line numbers debug dex old transpilations
Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
No comments. add comment
| Snippet ID: | #1009009 | 
| Snippet name: | saveTextFileWithEncoding | 
| Eternal ID of this version: | #1009009/1 | 
| Text MD5: | 6788740ff3017043fc454bc30f8c1285 | 
| Author: | stefan | 
| Category: | javax | 
| Type: | JavaX fragment (include) | 
| Public (visible to everyone): | Yes | 
| Archived (hidden from active list): | No | 
| Created/modified: | 2017-06-26 17:48:22 | 
| Source code size: | 1506 bytes / 36 lines | 
| Pitched / IR pitched: | No / No | 
| Views / Downloads: | 697 / 746 | 
| Referenced in: | [show references] |