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.

1  
/** writes safely (to temp file, then rename) */
2  
static File saveTextFile(String fileName, String contents) throws IOException {
3  
  CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
4  
  try {
5  
    File file = new File(fileName);
6  
    mkdirsForFile(file);
7  
    String tempFileName = fileName + "_temp";
8  
    File tempFile = new File(tempFileName);
9  
    if (contents != null) {
10  
      if (tempFile.exists()) try {
11  
        S saveName = tempFileName + ".saved." + now();
12  
        copyFile(tempFile, new File(saveName));
13  
      } catch (Throwable e) { printStackTrace(e); }
14  
      FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
15  
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
16  
      PrintWriter printWriter = new PrintWriter(outputStreamWriter);
17  
      printWriter.print(contents);
18  
      printWriter.close();
19  
    }
20  
    
21  
    if (file.exists() && !file.delete())
22  
      throw new IOException("Can't delete " + fileName);
23  
  
24  
    if (contents != null)
25  
      if (!tempFile.renameTo(file))
26  
        throw new IOException("Can't rename " + tempFile + " to " + file);
27  
        
28  
    ifndef LeanMode
29  
    vmBus_send('wroteFile, file);
30  
    endifndef
31  
    ret file;
32  
  } finally {
33  
    action.done();
34  
  }
35  
}
36  
37  
static File saveTextFile(File fileName, String contents) ctex {
38  
  saveTextFile(fileName.getPath(), contents);
39  
  ret fileName;
40  
}

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 22 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, dpqxeycirhfy, 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/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: 735 / 7067
Version history: 6 change(s)
Referenced in: [show references]