golang学习的点点滴滴:读写文件(面向对象版)

前端之家收集整理的这篇文章主要介绍了golang学习的点点滴滴:读写文件(面向对象版)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
packagemain

import(
	"fmt"
	"bufio"
	"io"
	"os"
	"flag"
	"strconv"
)

//定义一个结构体
typeReadWritestruct{
	In*string
	Out*string
}

//定义初始化方法
func(rw*ReadWrite)Init(){
	rw.In=flag.String("in","in","in")
	rw.Out=flag.String("out","out","out")
	flag.Parse()
}

//定义读文件方法
func(rw*ReadWrite)Read()(result[]int,errerror){
	file,err1:=os.Open(*(rw.In))

	ifnil!=err1{
		panic("errortoopenfile...")
	}

	deferfile.Close()

	br:=bufio.NewReader(file)
	result=make([]int,0)

	for{
		line,isPrefix,err2:=br.ReadLine()

		ifnil!=err2{
			ifio.EOF==err2{
				fmt.Println("finishread...")
			}
			break
		}

		ifisPrefix{
			return
		}

		str:=string(line)
		value,err3:=strconv.Atoi(str)

		ifnil!=err3{
			err=err3
			return
		}

		result=append(result,value)
	}

	return
}

//定义写文件方法
func(rw*ReadWrite)Write(value[]int){
	file,err:=os.Create(*(rw.Out))
	ifnil!=err{
		panic("errortocreatefile...")
	}

	deferfile.Close()

	forindex,res:=rangevalue{
		str:=strconv.Itoa(res*index)
		file.WriteString(str+"\n")
	}
}

funcmain(){
	deferfunc(){
			ifex:=recover();ex!=nil{
				fmt.Println(ex)
			}
		}()

	rw:=new(ReadWrite)
	rw.Init()
	value,err:=rw.Read()
	
	ifnil!=err{
		panic("error.....")
	}

	rw.Write(value)
}
原文链接:https://www.f2er.com/go/190751.html

猜你在找的Go相关文章