对于NetBeans插件,我想用特定的字符串和特定的字符集更改文件(在NetBeans编辑器中打开)的内容。为了实现这一点,我使用EditorCookie打开文件(一个DataObject),然后通过在数据对象的StyledDocument中插入不同的字符串来更改内容。
但是,我有一种感觉,文件总是保存为UTF-8。即使我在文件中写了一个文件标记。我做错了什么吗?
这是我的代码:
...
EditorCookie cookie = dataObject.getLookup().lookup(EditorCookie.class);
String utf16be = new String("\uFEFFHello World!".getBytes(StandardCharsets.UTF_16BE));
NbDocument.runAtomic(cookie.getDocument(), () -> {
try {
StyledDocument document = cookie.openDocument();
document.remove(0, document.getLength());
document.insertString(0, utf16be, null);
cookie.saveDocument();
} catch (BadLocationException | IOException ex) {
Exceptions.printStackTrace(ex);
}
});我也尝试过这种方法,但也不起作用:
...
EditorCookie cookie = dataObject.getLookup().lookup(EditorCookie.class);
NbDocument.runAtomic(cookie.getDocument(), () -> {
try {
StyledDocument doc = cookie.openDocument();
String utf16be = "\uFEFFHello World!";
InputStream is = new ByteArrayInputStream(utf16be.getBytes(StandardCharsets.UTF_16BE));
FileObject fileObject = dataObject.getPrimaryFile();
String mimePath = fileObject.getMIMEType();
Lookup lookup = MimeLookup.getLookup(MimePath.parse(mimePath));
EditorKit kit = lookup.lookup(EditorKit.class);
try {
kit.read(is, doc, doc.getLength());
} catch (IOException | BadLocationException ex) {
Exceptions.printStackTrace(ex);
} finally {
is.close();
}
cookie.saveDocument();
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
});发布于 2014-11-24 01:57:34
你的问题可能出在这里:
String utf16be = new String("\uFEFFHello World!".getBytes(StandardCharsets.UTF_16BE));它不会像你想的那样工作。这将使用UTF-16Little endian编码将字符串转换为字节数组,然后使用JRE的默认编码从这些字节创建一个String。
所以,这里有个陷阱:
A String 没有编码。
在Java语言中,这是一个char序列,这一点无关紧要。用'char‘代替’信鸽‘,净效果是一样的。
如果您想使用给定的编码将String写入字节流,则需要在您创建的Writer对象上指定所需的编码。类似地,如果您希望使用给定的编码将字节流读入String,则需要配置Reader以使用您想要的编码。
但是您的StyledDocument对象的方法名是.insertString();您应该按原样.insertString()您的String对象;不要这样转换它,因为如上所述,这是被误导的。
https://stackoverflow.com/questions/27092231
复制相似问题