使用 Go 从连接读取 utf8 编码的数据
我可以使用 io.WriteString 轻松地将字符串写入连接。
但是,我似乎无法轻松地从连接读取字符串。我可以从连接中读取的唯一内容是字节,看来我必须以某种方式将其转换为字符串。
假设字节表示 utf8 编码的字符串,我如何将它们转换为字符串形式?
(编辑:或者,我怎样才能简单地从连接中读取字符串?)
谢谢!
I can easily write a string to a connection using io.WriteString.
However, I can't seem to easily read a string from a connection. The only thing I can read from the connection are bytes, which, it seems, I must then somehow convert into a string.
Assuming the bytes represent a utf8-encoded string, how would I convert them to string form?
(Edit: alternatively, how could I simply read a string from a connection?)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将字节切片转换为字符串:
不涉及编码/解码,因为字符串仅被视为字节数组。
You can just cast a slice of bytes into a string:
There is no encoding/decoding involved, because strings are just treated as arrays of bytes.
可以在标准库中找到适合您目的的方便工具:
bytes.Buffer
(请参阅包文档)。假设您有一个实现 io.Reader 的对象(也就是说,它有一个带有签名的方法 Read([]byte) (int, os.Error) )。
一个常见的示例是 os.File:
如果您想将该文件的内容读入字符串,只需创建一个 bytes.Buffer(其零值是即用型缓冲区,因此您无需调用构造函数):
使用 io.Copy 将文件内容复制到缓冲区中:(
使用 io.Copy 的替代方法 将是
b.ReadFrom(f)
- 它们或多或少是相同的。)并调用缓冲区的 String 方法以字符串形式检索缓冲区的内容:
bytes .Buffer
会自动增长以存储文件的内容,因此您无需担心分配和增长byte
切片等问题。A handy tool that will suit your purpose can be found in the standard library:
bytes.Buffer
(see the package docs).Say you have an object that implements
io.Reader
(that is, it has a method with the signatureRead([]byte) (int, os.Error)
).A common example is an
os.File
:If you wanted to read the contents of that file into a string, simply create a
bytes.Buffer
(its zero-value is a ready-to-use buffer, so you don't need to call a constructor):Use
io.Copy
to copy the file's contents into the buffer:(An alternative to using
io.Copy
would beb.ReadFrom(f)
- they're more or less the same.)And call the buffer's String method to retrieve the buffer's contents as a string:
The
bytes.Buffer
will automatically grow to store the contents of the file, so you don't need to worry about allocating and growingbyte
slices, etc.