How to read a file into a string in GoLang
The Go language provides a lot of file manipulation tools, one of which is how to read files into strings. ioutil.ReadFile()
, File.Read()
, buf.ReadFrom()
and strings.Builder are just a few of the methods that can be used to efficiently write file contents to strings.
Using ioutil.ReadFile() method in Go
package main
import
(
"fmt"
"io/ioutil"
)
func main() {
inputData := []byte("Hello, World!")
err := ioutil.WriteFile("File.txt", inputData, 0777)
Data, err := ioutil.ReadFile("File.txt")
if err != nil {
fmt.Println(err)
}
fmt.Print(string(Data))
}
Output:
Hello, World!
The above code allows us to create a new file and write data to it. We then use the ioutil.ReadFile() method to read the created file.
Using File.Read() method in Go
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"io"
)
func main() {
inputData := []byte("Hello, World!")
err := ioutil.WriteFile("file.txt", inputData, 0777)
f, err := os.Open("file.txt")
if err != nil {
log.Fatalf("Error in reading file: %v", err)
}
defer f.Close()
buf := make([]byte, 1024)
for {
n, err := f.Read(buf)
if err == io.EOF {
break
}
if err != nil {
fmt.Println(err)
continue
}
if n > 0 {
fmt.Println(string(buf[:n]))
}
}
}
Output:
Hello, World!
In the code above, we read the file by splitting it. We specify the buffer size to read each time and then allocate only len(buf) in memory.
The file is then read in segments with each iteration. This method is mainly used for large files where the contents of the file cannot fit completely into memory.
Using buf.ReadFrom() method in Go
package main
import (
"fmt"
"io/ioutil"
"os"
"bytes"
"log"
)
func main() {
inputData := []byte("Hello, World!")
err := ioutil.WriteFile("File.txt", inputData, 0777)
f, err := os.Open("File.txt")
if err != nil{
log.Fatal(err)
}
defer f.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(f)
data := buf.String()
fmt.Print(data)
}
Output:
Hello, World!
In the above code, we have used buf.ReadFrom()
readData from the file until EOF and appended it to a buffer; the buffer size grows as needed.
Using strings.Builder methods in Go
package main
import (
"io/ioutil"
"io"
"os"
"strings"
)
func main() {
inputData := []byte("Hello, World!")
err := ioutil.WriteFile("file.txt", inputData, 0777)
f, err := os.Open("file.txt")
if err != nil {
panic(err)
}
defer f.Close()
b := new(strings.Builder)
io.Copy(b, f)
print(b.String())
}
Output:
Hello, World!
In the above code, strings.Builder concatenates the strings. The data is read from the file one by one and then printed together.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Install GoLang using Brew
Publish Date:2025/04/15 Views:82 Category:Go
-
This article describes how to install GoLang using Brew on Linux or macOS. Install GoLang using Brew brew installs missing packages in Linux and macOS. It makes it easy to install GoLang on Linux or macOS. Follow the steps below to install
GoLang RWMutex Detailed Introduction
Publish Date:2025/04/15 Views:116 Category:Go
-
This article introduces how to use rwmutex in Go language. Go language RWMutex mutex is the abbreviation of mutual exclusion, which is used to keep track of which thread has accessed a variable at any time. Mutex is a data structure provide
Enabling CORS in GoLang
Publish Date:2025/04/15 Views:102 Category:Go
-
This article describes how to enable and use CORS in GoLang. Go language CORS Cross-origin resource sharing (CORS) is a process based on HTTP headers that defines the origins from which browsers are allowed to load and use resources. CORS i
Function pointers in Go
Publish Date:2025/04/15 Views:83 Category:Go
-
A pointer in Go is a special-purpose variable that stores the memory address of other variables and the point where the memory is located. It can also access the value stored in that memory location. Pointer declaration in Go var pointer_na
Duration in Go
Publish Date:2025/04/15 Views:89 Category:Go
-
Go duration conversion can be done in a variety of ways. The time library and the time.duration method are often used to calculate and display time. Note that duration refers to the time elapsed between two defined time objects, as an int64
Create a new directory in Go
Publish Date:2025/04/15 Views:112 Category:Go
-
Go has many ways to create directories, one of which is os.Mkdir . We can assign specified names and permission bits to the newly formed directory. os.MkdirAll Useful for recursively creating multiple directories, including any missing pare
Getting a string representation of a structure in Go
Publish Date:2025/04/15 Views:63 Category:Go
-
Go allows us to serialize data from structures using a variety of simple standard methods. Converting a structure to a string using String method in Go The GoLang package String helps implement simple functions to manipulate and edit UTF-8
Convert JSON to struct in Go
Publish Date:2025/04/15 Views:126 Category:Go
-
This article describes how to convert JSON to struct in GoLang . Convert JSON to Struct using Unmarshal method in Go The encoding/json package of the Go language provides a function Unmarshal to convert JSON data into byte format. This func
在 Golang 中使用 If-Else 和 Switch Loop Inside HTML 模板
Publish Date:2023/04/27 Views:104 Category:Go
-
本篇文章介绍了在 Golang 的 HTML 模板中使用 if-else 和 switch 循环。因此,只要输出是 HTML,就应该始终使用 HTML 模板包而不是文本模板。