Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

25
LINES

< > BotCompany Repo | #1001113 // saveBinaryFile

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (9250L/51K).

/** writes safely (to temp file, then rename) */
public static byte[] saveBinaryFile(String fileName, byte[] contents) ctex {
  File file = new File(fileName);
  File parentFile = file.getParentFile();
  if (parentFile != null)
    parentFile.mkdirs();
  String tempFileName = fileName + "_temp";
  try (FileOutputStream fileOutputStream = newFileOutputStream(tempFileName)) {
    fileOutputStream.write(contents);
  }
  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);
    
  ifndef LeanMode
  vmBus_send('wroteFile, file);
  endifndef
  ret contents;
}

static byte[] saveBinaryFile(File fileName, byte[] contents) {
  ret saveBinaryFile(fileName.getPath(), contents);
}

Author comment

Began life as a copy of #2000464

download  show line numbers  debug dex  old transpilations   

Travelled to 16 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1001113
Snippet name: saveBinaryFile
Eternal ID of this version: #1001113/5
Text MD5: 01937b87a511127498dc8f4d902ba013
Transpilation MD5: 6e177032ef863336057736f8ff3180cc
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-08-07 02:47:16
Source code size: 865 bytes / 25 lines
Pitched / IR pitched: No / No
Views / Downloads: 677 / 3444
Version history: 4 change(s)
Referenced in: #1002427 - Accellerating 629 (SPIKE)
#1006654 - Standard functions list 2 (LIVE, continuation of #761)
#1009237 - saveBinaryProgramFile
#1034335 - saveBinaryFile_simple
#3000382 - Answer for ferdie (>> t = 1, f = 0)