File Handling using methods

How to read/write in form of maps in the files in Golang.For ex:- if f is an object of type file struct then if i need to implement f.write(“key”,“value”) in the file such that fmt.Println(f.read(“key”)) should yield value?

There is no type in the standard library that does this. But you can use a simple library like github.com/magiconair/properties.


package main

import (
	"fmt"
	"io/ioutil"
	"log"

	// https://pkg.go.dev/github.com/magiconair/properties?
	"github.com/magiconair/properties"
)

func main() {
	// Declare a properties instance and put some values into it.
	p := properties.NewProperties()
	p.Set("key1", "value1")
	p.Set("key2", "value2")

	// Open a temporary file.
	tmpfile, err := ioutil.TempFile("", "*.properties")
	if err != nil {
		log.Panic(err)
	}

	// Remember the filename.
	fn := tmpfile.Name()

	// Write the properties to the file.
	_, err = p.Write(tmpfile, properties.UTF8)
	if err != nil {
		log.Panic(err)
	}

	err = tmpfile.Close()
	if err != nil {
		log.Panic(err)
	}

	// Now read the properties back in.
	q := properties.MustLoadFile(fn, properties.UTF8)

	// And print the value for one of the used keys.
	v, ok := q.Get("key1")
	if ok {
		fmt.Println(v)
	} else {
		fmt.Println("key1 missing")
	}
}

Well, you should have included this in your first post. This looks like an exercise. What have you tried to solve it? Does it work?

BTW: Please indent code using the </> button at the top of the edit field. Right now it is very hard to read.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.