JXA:写入文件时设置UTF-8编码 [英] JXA: Set UTF-8 encoding when writing files

查看:123
本文介绍了JXA:写入文件时设置UTF-8编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用standardadditions编写文本文件,显然可以在参数包中配置编码.在AppleScript中,我将编写《 utf8类》,但是在JXA中使用哪个值?我尝试了字符串"UTF8","utf8","class utf8",但没有成功.错误始终是:错误:无法转换类型.(-1700)".如果我使用文本",则该文件是用MACROMAN编写的.

If I write a textfile using the standardadditions, I obviously can configure the encoding in a parameter bag. In AppleScript I would write «class utf8» but which value to use in JXA? I tried the Strings "UTF8", "utf8", "class utf8" without success. The Error is always: "Error: Can't convert types. (-1700)". If I use "text" the file is written in 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回答后加上:

我阅读了文档

代替使用ObjectiveC桥.这个例子有效

to use the ObjectiveC bridge instead. This example works

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

如果我理解正确,下面的示例应该可以工作,因为约定如何在桥内命名ObjectiveC方法(删除冒号,添加驼峰大写字母),但事实并非如此.没有文件被写入,返回值为false.

If I understand correctly, the following example should work, because of the convention how ObjectiveC Methods are named within the bridge (remove colon, add camelcase), but it doesn't. No file has been written and the returnvalue is false.

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

我错了什么?我什至不知道如何将正确的Errorhandler传递为第4个参数,以及第3个参数是否具有正确的值.

What did I wrong? I do not even know how to pass in a proper Errorhandler as 4th parameter and if the 3rd param has the proper value.

推荐答案

请尝试

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

在这里工作!可用的编码在NSString文档中列出(请参见链接)!
迈克尔,汉堡,请尽情享受

Worked here! The available encodings are listed inside the NSString documentation (see your link)!
Enjoy, Michael / Hamburg

这篇关于JXA:写入文件时设置UTF-8编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆