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

40
LINES

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

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

Transpiled version (1885L) is out of date.

/** writes safely (to temp file, then rename) */
static File saveTextFile(String fileName, String contents) throws IOException {
  CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
  try {
    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); }
      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;
  } finally {
    action.done();
  }
}

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   

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

No comments. add comment

Snippet ID: #1001042
Snippet name: saveTextFile (function)
Eternal ID of this version: #1001042/7
Text MD5: 6fae685711567e1ebb4464352229d9b2
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-05-27 14:59:42
Source code size: 1470 bytes / 40 lines
Pitched / IR pitched: No / No
Views / Downloads: 593 / 6821
Version history: 6 change(s)
Referenced in: [show references]

Formerly at http://tinybrain.de/1001042 & http://1001042.tinybrain.de