1 | /** writes safely (to temp file, then rename) */ |
2 | public static void saveBinaryFile(String fileName, byte[] 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 | fileOutputStream.write(contents); |
10 | fileOutputStream.close(); |
11 | if (file.exists() && !file.delete()) |
12 | throw new IOException("Can't delete " + fileName); |
13 | |
14 | if (!new File(tempFileName).renameTo(file)) |
15 | throw new IOException("Can't rename " + tempFileName + " to " + fileName); |
16 | } |
Snippet is not live.
Travelled to 12 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
No comments. add comment
Snippet ID: | #2000464 |
Snippet name: | saveBinaryFile |
Eternal ID of this version: | #2000464/1 |
Text MD5: | ce96010e729ba87857ae72fbf11f163b |
Author: | stefan |
Category: | javax |
Type: | New Tinybrain snippet |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2015-07-26 20:21:39 |
Source code size: | 715 bytes / 16 lines |
Pitched / IR pitched: | No / Yes |
Views / Downloads: | 618 / 1811 |
Referenced in: | [show references] |