dougong5285
2014-09-03 18:44
浏览 44
已采纳

Go中是否有等效的java.io.Reader?

Go has very nice io.Reader and io.Writer interfaces, that roughly correspond to java.io.InputStream and java.io.OutputStream 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 java.io.Reader (stream of characters) and java.io.Writer (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")
stringReader.read(128)

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中的 java.io.InputStream java.io.OutputStream 类(即io.Reader =字节流,io.Writer =下沉

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

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

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

阅读器部分,读取下一个128个字节,并使用ISO-8859-2字符集对字节进行解码,从而返回Go字符串。

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

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

 
stringWriter:= NewStringWriter(writer,“ utf16be”)
stringWriter.write(“馞鮂褗褆諓”); 
 <  / 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
    io.WriteString("stuff")
    
    // r = io.Reader
    sc := bufio.NewScanner(r)
    for scanner.Scan() {
        fmt.Println(sc.Text())
    }
    

    strings are a readonly []byte more or less.

    //edit

    After reading the comments, I think you're looking for https://code.google.com/p/go-charset:

    r, err := charset.NewReader("latin1", r)
    if err != nil {
            log.Fatal(err)
    }
    result, err := ioutil.ReadAll(r)
    if err != nil {
            log.Fatal(err)
    }
    fmt.Printf("%s
    ", result)
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题