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

39
LINES

< > BotCompany Repo | #1001042 // saveTextFile (function)

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

Transpiled version (5130L) is out of date.

/** writes safely (to temp file, then rename) */
static File saveTextFile(String fileName, String contents) throws IOException {
  /*ifdef CriticalActions
  temp beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
  endifdef*/
  
  File file = new File(fileName);
  mkdirsForFile(file);
  String tempFileName = fileName + "_temp";
  File tempFile = new File(tempFileName);
  if (contents != null) {
    if (tempFile.exists()) try {
      S saveName = tempFileName + ".saved." + now();
      copyFile(tempFile, new File(saveName));
    } catch (Throwable e) { printStackTrace(e); }
    temp FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
    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 (contents != null)
    if (!tempFile.renameTo(file))
      throw new IOException("Can't rename " + tempFile + " to " + file);
      
  ifndef LeanMode
  vmBus_send('wroteFile, file);
  endifndef
  ret file;
}

static File saveTextFile(File fileName, String contents) ctex {
  saveTextFile(fileName.getPath(), contents);
  ret fileName;
}

Author comment

Began life as a copy of #2000323

Can now handle "null" contents (deletes file)

download  show line numbers  debug dex  old transpilations   

Travelled to 23 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, dpqxeycirhfy, ekrmjmnbrukm, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, jtubtzbbkimh, lpdgvwnxivlt, mqqgnosmbjvj, omdjrrnzbjjv, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, skddmizpvtmy, tslmcundralx, tvejysmllsmz, vouqrxazstgt, whxojlpjdney, xrpafgyirdlv, yanjaxplzisb

No comments. add comment

Snippet ID: #1001042
Snippet name: saveTextFile (function)
Eternal ID of this version: #1001042/10
Text MD5: b59195fadef76f6178260d6dee014a1e
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-04-30 15:05:56
Source code size: 1398 bytes / 39 lines
Pitched / IR pitched: No / No
Views / Downloads: 832 / 7228
Version history: 9 change(s)
Referenced in: [show references]