英文:
Is there java.io.Reader equivalent in Go?
问题
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 + 字符串类型转换几乎可以免费实现UTF8编码)。
更新:我想我的描述可能有些混淆,我应该避免与Java的东西进行比较。我想要的是这样的:
读取部分,读取下一个128个字节,并使用ISO-8859-2字符集解码字节,返回Go字符串。
stringReader := NewStringReader(reader, "iso-8859-2")
stringReader.read(128)
写入部分,将内容转换为UTF16-BE字节,并将其写入写入器:
stringWriter := NewStringWriter(writer, "utf16be")
stringWriter.write("馞鮂 擙樲橚 褗褆諓");
英文:
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.
<pre>
stringReader := NewStringReader(reader, "iso-8859-2")
stringReader.read(128)
</pre>
Writer part, convert stuff to UTF16-BE bytes, and write it to the writer:
<pre>
stringWriter := NewStringWriter(writer, "utf16be")
stringWriter.write("馞鮂 擙樲橚 褗褆諓");
</pre>
答案1
得分: 3
我对Java不够熟悉,但是这段代码不是做同样的事情吗:
// w = io.Writer
io.WriteString("stuff")
// r = io.Reader
sc := bufio.NewScanner(r)
for scanner.Scan() {
fmt.Println(sc.Text())
}
字符串在大致上是一个只读的[]byte。
//编辑
阅读了评论后,我认为你正在寻找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\n", result)
英文:
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\n", result)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论