How to write text to a text file by Photoshop JavaScript?

前端 未结 5 697
隐瞒了意图╮
隐瞒了意图╮ 2021-02-07 17:50

I took a look at Photoshop CS5 Scripting Guide and Photoshop CS5 JavaScript Reference, but I couldn\'t find out a method to write text to a plain text file. Is there any way to

5条回答
  •  温柔的废话
    2021-02-07 18:20

    I have read the docs and combined best parts of psycho brm's and corrin_m's answer.
    MY ANSWER ALSO CHECKS FOR ERRORS.

    It is not necessary to delete file if it exists because opening with "w" will overwrite existing file it.

    /* =======================================================
     * Saves file as text. Overwrites old file if exists.
     * Returns empty string if no errors, otherwise error message.
     * =======================================================*/
    function saveAsTextFile(filePath, content) {
        var saveFile = new File(filePath);
    
        saveFile.encoding = "UTF8";
        saveFile.open("w");
        if (saveFile.error != "")
            return saveFile.error;
    
        saveFile.write(content);
        if (saveFile.error != "")
            return saveFile.error;
    
        saveFile.close();
        if (saveFile.error != "")
            return saveFile.error;
    
        return "";
    }
    

    This is how I am using the function in my scripts

    error = saveAsTextFile(filePath, content);
    if (error === "") {
      alert(filePath + " saved OK.");
    }
    else {
      alert("Error saving " + filePath + "\n" + error);
    }
    

    BTW I am keeping this in separate file called common-code.jsx and I can include it with following line (single line comments are intentional).

    // @include 'common-code.jsx'
    

提交回复
热议问题