1 | /** writes safely (to temp file, then rename) */ |
2 | static void saveTextFileWithEncoding(String fileName, String contents, S encoding) throws IOException { |
3 | CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)"); |
4 | try { |
5 | File file = new File(fileName); |
6 | File parentFile = file.getParentFile(); |
7 | if (parentFile != null) |
8 | parentFile.mkdirs(); |
9 | String tempFileName = fileName + "_temp"; |
10 | File tempFile = new File(tempFileName); |
11 | if (contents != null) { |
12 | if (tempFile.exists()) try { |
13 | S saveName = tempFileName + ".saved." + now(); |
14 | copyFile(tempFile, new File(saveName)); |
15 | } catch (Throwable e) { printStackTrace(e); } |
16 | FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); |
17 | OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, encoding); |
18 | PrintWriter printWriter = new PrintWriter(outputStreamWriter); |
19 | printWriter.print(contents); |
20 | printWriter.close(); |
21 | } |
22 | |
23 | if (file.exists() && !file.delete()) |
24 | throw new IOException("Can't delete " + fileName); |
25 | |
26 | if (contents != null) |
27 | if (!tempFile.renameTo(file)) |
28 | throw new IOException("Can't rename " + tempFile + " to " + file); |
29 | } finally { |
30 | action.done(); |
31 | } |
32 | } |
33 | |
34 | static void saveTextFileWithEncoding(File fileName, String contents, S encoding) ctex { |
35 | saveTextFileWithEncoding(fileName.getPath(), contents, encoding); |
36 | } |
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: | 460 / 502 |
Referenced in: | [show references] |