Skip to content
KerwinKoo edited this page Dec 29, 2015 · 2 revisions
---
title: Golang File IO Operations
date: 2015-11-18 16:07:54
tags: [Go]
filename: Golang_File_IO_Operations
categories: Go
---

1 Read File into []byte in Package:ioutil


func readFileIntoByte(filename string) []byte {
	var fmwConfigJsonBuf []byte

	fin, err := os.Open(filename)

	if err != nil {
		panic(err)
	} else {
		fmwConfigJsonBuf, err = ioutil.ReadAll(fin)
		if err != nil {
			panic(err)
		}
	}
	fin.Close()
	return fmwConfigJsonBuf
}

2 File Copy


// CopyFile copies a file from src to dst. If src and dst files exist, and are
// the same, then return success. Otherise, attempt to create a hard link
// between the two files. If that fail, copy the file contents from src to dst.
func copyFile(src, dst string) error {
	sfi, err := os.Stat(src)
	if err != nil {
		return err
	}
	if !sfi.Mode().IsRegular() {
		// cannot copy non-regular files (e.g., directories,
		// symlinks, devices, etc.)
		return fmt.Errorf("CopyFile: non-regular source file %s (%q)", sfi.Name(), sfi.Mode().String())
	}
	dfi, err := os.Stat(dst)
	if err != nil {
		if !os.IsNotExist(err) {
			return err
		}
	} else {
		if !(dfi.Mode().IsRegular()) {
			return fmt.Errorf("CopyFile: non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String())
		}
		if os.SameFile(sfi, dfi) {
			return err
		}
	}
	if err = os.Link(src, dst); err == nil {
		return err
	}
	err = copyFileContents(src, dst)
	return err
}

// copyFileContents copies the contents of the file named src to the file named
// by dst. The file will be created if it does not already exist. If the
// destination file exists, all it's contents will be replaced by the contents
// of the source file.
func copyFileContents(src, dst string) (err error) {
	in, err := os.Open(src)
	if err != nil {
		return
	}
	defer in.Close()
	out, err := os.Create(dst)
	if err != nil {
		return
	}
	defer func() {
		cerror := out.Close()
		if err == nil {
			err = cerror
		}
	}()
	if _, err = io.Copy(out, in); err != nil {
		return
	}
	err = out.Sync()
	return
}

3 List files from directory


//listFiles show the file list in directory
func listFiles(dirname string) []string {
	fileList := []string{}
	files, _ := ioutil.ReadDir(dirname)
	for _, fileInfo := range files {
		if !fileInfo.IsDir() {
			fileList = append(fileList, fileInfo.Name())
		}
	}
	return fileList
}

4 Check path existing or not

if _, err := os.Stat(DefaultContent); !os.IsNotExist(err) {
		log.Fatalf("Already has default config:%s", DefaultContent)
}

5 Remove directory and its' contents

if err := os.RemoveAll(filePath); err != nil {
		panic(err)
}

6 Change relative path into abs path

import "path/filepath"

uploads, _ := filepath.Abs(uploadPath)

[[TOC]]

Clone this wiki locally