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: 754 / 3543
Version history: 4 change(s)
Referenced in: [show references]