JXA:写入文件时设置 UTF-8 编码 [英] JXA: Set UTF-8 encoding when writing files
问题描述
如果我使用标准添加编写文本文件,我显然可以在参数包中配置编码.在 AppleScript 中我会写 «class 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 的回答后添加:
Addition after foo's answer:
I read the relevant paragraphs in the documentation https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/index.html#//apple_ref/doc/uid/TP40014508-CH109-SW17
和
改为使用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屋!