【问题标题】:JXA: Set UTF-8 encoding when writing filesJXA:写入文件时设置 UTF-8 编码
【发布时间】:2015-05-18 13:47:18
【问题描述】:

如果我使用标准添加编写文本文件,我显然可以在参数包中配置编码。在 AppleScript 中我会写 «class utf8» 但在 JXA 中使用哪个值? 我尝试了字符串“UTF8”、“utf8”、“class utf8”但没有成功。错误总是:“错误:无法转换类型。(-1700)”。如果我使用“文本”,则文件是用 MACROMAN 编写的。

下面的独立示例:

var exportFileWriter = fileWriter('/Users/norman/mini.txt');
exportFileWriter.write('äöü');
exportFileWriter.close();


function fileWriter(pathAsString) {
    'use strict';

    var app = Application.currentApplication();
    app.includeStandardAdditions = true;

    var path = Path(pathAsString);
    var file = app.openForAccess(path, {writePermission: true});

    /* reset file length */
    app.setEof(file, {to: 0});

    return {
        write: function(content) {
            /* How can I write UTF-8? */
            app.write(content, {to: file, as: 'text'});
        },
        close: function() {
            app.closeAccess(file);
        }
    };
}

在 foo 的回答之后添加:

我阅读了文档https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/index.html#//apple_ref/doc/uid/TP40014508-CH109-SW17中的相关段落

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/instm/NSString/writeToFile:atomically:encoding:error:

改为使用 ObjectiveC 桥接器。这个例子有效

str = $.NSString.alloc.initWithUTF8String('foo')
str.writeToFileAtomically('/tmp/foo', true)

如果我理解正确,以下示例应该可以工作,因为在桥中如何命名 ObjectiveC 方法的约定(删除冒号,添加驼峰式),但它没有。没有写入文件,返回值为false。

str = $.NSString.alloc.initWithUTF8String('foo')
str.writeToFileAtomicallyEncodingError('/tmp/foo', true, 'UTF-8', null);

我做错了什么?我什至不知道如何将正确的错误处理程序作为第四个参数传递,以及第三个参数是否具有正确的值。

【问题讨论】:

    标签: utf-8 applescript osx-yosemite javascript-automation


    【解决方案1】:

    请尝试

    str = $.NSString.alloc.initWithUTF8String('foo');
    str.writeToFileAtomicallyEncodingError('/tmp/foo', true, $.NSUTF8StringEncoding, null);
    

    在这里工作! NSString 文档中列出了可用的编码(请参阅您的链接)!
    享受吧,迈克尔/汉堡

    【讨论】:

    • 打败我!我刚刚发布了同样的答案,这也对我有用。
    • 谢谢。它运作良好。如果我有足够的声誉,我会赞成你和 foo 的回答。在 foo 提出 ObjC Bridge 之前,我的解决方法是使用 node.js 并要求 'encoding': encoding.convert(data, 'UTF-8', 'MACROMAN'); Grüsse aus Zürich nach Hamburg。
    【解决方案2】:

    JXA 的 Apple 事件桥存在许多缺陷和缺失的功能(例如,使用原始 AE 代码的能力)。改用它的 ObjC 桥接器;见-[NSString writeToFile:atomically:encoding:error:]

    【讨论】:

    • 感谢您的意见。我阅读了一些文档,编辑了我的问题并添加了一些最小的示例。
    猜你喜欢
    • 2021-05-25
    • 2014-07-01
    • 1970-01-01
    • 2011-06-30
    • 2011-07-07
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 2012-05-26
    相关资源
    最近更新 更多