1 | /** writes safely (to temp file, then rename) */ |
2 | public static void saveTextFile(String fileName, String contents) throws IOException { |
3 | File file = new File(fileName); |
4 | File parentFile = file.getParentFile(); |
5 | if (parentFile != null) |
6 | parentFile.mkdirs(); |
7 | String tempFileName = fileName + "_temp"; |
8 | FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); |
9 | OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); |
10 | PrintWriter printWriter = new PrintWriter(outputStreamWriter); |
11 | printWriter.print(contents); |
12 | printWriter.close(); |
13 | if (file.exists() && !file.delete()) |
14 | throw new IOException("Can't delete " + fileName); |
15 | |
16 | if (!new File(tempFileName).renameTo(file)) |
17 | throw new IOException("Can't rename " + tempFileName + " to " + fileName); |
18 | } |
Snippet is not live.
Travelled to 12 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
ID | Author/Program | Comment | Date |
---|---|---|---|
260 | #1000604 (pitcher) | 2015-08-18 00:53:20 | |
227 | #1000610 (pitcher) | Edit suggestion: !636 !629 main { static Object androidContext; static String programID; public static void main(String[] args) throws Exception { /** writes safely (to temp file, then rename) */ public static void saveTextFile(String fileName, String contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); } }} | 2015-08-18 00:51:52 |
Snippet ID: | #2000323 |
Snippet name: | saveTextFile (function) |
Eternal ID of this version: | #2000323/1 |
Text MD5: | 57b2da3af1bf29b9105d00733b308304 |
Author: | stefan |
Category: | javax |
Type: | New Tinybrain snippet |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2015-04-28 20:18:46 |
Source code size: | 865 bytes / 18 lines |
Pitched / IR pitched: | No / Yes |
Views / Downloads: | 860 / 5417 |
Referenced in: | [show references] |