2014-09-03 18:44
浏览 44


Go has very nice io.Reader and io.Writer interfaces, that roughly correspond to and classes in Java (i.e. io.Reader = stream of bytes, io.Writer = sink for bytes).

I'm wondering, if Go also has some equivalent of (stream of characters) and (sink for characters) classes.

What I want is to read/write string from/to stream, without thinking about the encoding all the time + support for different encodings than just UTF8 (which is what combination of io.Reader + string typecasting gives me almost for free).

Update: so I guess my description is confusing, and I should have avoided comparison to Java stuff. What I want is something like this:

Reader part, read next 128 bytes, and return Go string by decoding bytes using ISO-8859-2 charset.

stringReader := NewStringReader(reader, "iso-8859-2")

Writer part, convert stuff to UTF16-BE bytes, and write it to the writer:

stringWriter := NewStringWriter(writer, "utf16be")
stringWriter.write("馞鮂 擙樲橚 褗褆諓");

图片转代码服务由CSDN问答提供 功能建议

Go的 io.Reader io.Writer 接口,这些接口大致对应于Java中的 类(即io.Reader =字节流,io.Writer =下沉

我想知道Go是否还具有与 (字符流)和 java等效的功能。 io.Writer (用于字符的接收器)类。

我想要的是从流中读取/写入字符串,而无需一直考虑编码+支持 除了UTF8以外,还有其他不同的编码(io.Reader +字符串类型转换的组合几乎免费提供给我)。

更新:所以我想我的描述是 令人困惑,我应该避免与Java东西进行比较。 我想要的是这样的东西:


stringReader:= NewStringReader(reader,“ iso-8859-2”)

书写器部分,将内容转换为UTF16-BE字节, 并将其写入作者:

stringWriter:= NewStringWriter(writer,“ utf16be”)
 <  / pre> 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongpo4197 2014-09-03 19:23

    I'm not familiar enough with Java but wouldn't this do the same thing:

    // w = io.Writer
    // r = io.Reader
    sc := bufio.NewScanner(r)
    for scanner.Scan() {

    strings are a readonly []byte more or less.


    After reading the comments, I think you're looking for

    r, err := charset.NewReader("latin1", r)
    if err != nil {
    result, err := ioutil.ReadAll(r)
    if err != nil {
    ", result)
    解决 无用
    打赏 举报

相关推荐 更多相似问题