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

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("馞鮂 擙樲橚 褗褆諓");
  • 写回答

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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划