如何使用特定的字符集写入StyledDocument?

时间:2014-11-23 17:51:55

标签: java netbeans character-encoding netbeans-platform styleddocument

对于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);
  }
});

1 个答案:

答案 0 :(得分:1)

你的问题可能就在这里:

String utf16be = new String("\uFEFFHello World!".getBytes(StandardCharsets.UTF_16BE));

这不符合你的想法。这将使用UTF-16小端编码将您的字符串转换为字节数组,然后使用JRE的默认编码从这些字节创建String

所以,这就是问题:

String没有编码。

在Java中,这是一个char的序列并不重要。将“char”替换为“载体鸽”,净效应将是相同的。

如果要将String写入具有给定编码的字节流,则需要在创建的Writer对象上指定所需的编码。同样,如果您想使用给定的编码将字节流读入String,则需要配置Reader以使用所需的编码。

但您的StyledDocument对象的方法名称为.insertString();您应该.insertString() String对象;不要像你那样改变它,因为这是错误的,如上所述。