2

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

1 回答 1

1

你的问题可能在这里:

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

这不会像你认为的那样做。这将使用 UTF-16 little endian 编码将您的字符串转换为字节数组,然后String使用 JRE 的默认编码从这些字节创建一个。

所以,这里有一个问题:

AString没有编码。

在 Java 中这是一个chars 序列这一事实并不重要。用“char”代替“信鸽”,净效果是一样的。

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

但是您的StyledDocument对象的方法名称是.insertString(); 您应该按原样处理.insertString()您的String对象;不要按照你的方式改造它,因为这是错误的,如上所述。

于 2014-11-23T17:57:34.100 回答