-
Create an empty file
package main import ( "log" "os" ) func main() { emptyFile, err := os.Create("empty.txt") if err != nil { log.Fatal(err) } log.Println(emptyFile) emptyFile.Close() }
Output :
PS C:\GO_Language\file> go run empty.go 2022/08/20 15:45:16 &{0xc00007e780}
-
Create directory
package main import ( "log" "os" ) func main() { _, err := os.Stat("text") if os.IsNotExist(err) { errDir := os.MkdirAll("text", 0755) if errDir != nil { log.Fatal(err) } } }
Output :
PS C:\GO_Language\file> go run create.go
-
Rename a file
package main import ( "log" "os" ) func main() { oldName := "test.txt" newName := "testing.txt" err := os.Rename(oldName, newName) if err != nil { log.Fatal(err) } }
Output :
PS C:\GO_Language\file> go run rename.go
-
Copy file at the specified location
package main import ( "io" "log" "os" ) func main() { sourceFile, err := os.Open("C:/GO_Language/file/test.txt") if err != nil { log.Fatal(err) } defer sourceFile.Close() // Create new file newFile, err := os.Create("C:/GO_Language/test.txt ") if err != nil { log.Fatal(err) } defer newFile.Close() bytesCopied, err := io.Copy(newFile, sourceFile) if err != nil { log.Fatal(err) } log.Printf("Copied %d bytes.", bytesCopied) }
Output :
PS C:\GO_Language\file> go run f1.go 2022/08/20 15:39:48 Copied 59 bytes.
-
Move a File
package main import ( "log" "os" ) func main() { oldLocation := "C:/GO_Language/test.txt" newLocation := "C:/GO_Language/file/test.txt" err := os.Rename(oldLocation, newLocation) if err != nil { log.Fatal(err) } }
Output :
PS C:\GO_Language\file> go run move.go
-
Getting Metadata of a file
package main import ( "fmt" "log" "os" ) func main() { fileStat, err := os.Stat("test.txt") if err != nil { log.Fatal(err) } fmt.Println("File Name:", fileStat.Name()) fmt.Println("Size:", fileStat.Size()) fmt.Println("Permissions:", fileStat.Mode()) fmt.Println("Last Modified:", fileStat.ModTime()) fmt.Println("Is Directory: ", fileStat.IsDir()) }
Output :
PS C:\GO_Language\file> go run matadata.go File Name: test.txt Size: 59 Permissions: -rw-rw-rw- Last Modified: 2022-08-20 15:39:48.8907731 +0530 IST Is Directory: false
-
Deleting a specific file
package main import ( "log" "os" ) func main() { err := os.Remove("C:/GO_Language/test.txt ") if err != nil { log.Fatal(err) } }
Output :
PS C:\GO_Language\file> go run delete.go
-
Read a text file character by character
package main import ( "bufio" "fmt" "io/ioutil" "os" "strings" ) func main() { filename := "test.txt" filebuffer, err := ioutil.ReadFile(filename) if err != nil { fmt.Println(err) os.Exit(1) } inputdata := string(filebuffer) data := bufio.NewScanner(strings.NewReader(inputdata)) data.Split(bufio.ScanRunes) for data.Scan() { fmt.Print(data.Text()) } }
Output :
PS C:\GO_Language\file> go run readchar.go Sandeep Ramesh Shankar Mohan dhanaji Rajya Sohel
-
Truncate File Content
package main import ( "log" "os" ) func main() { err := os.Truncate("test.txt", 100) if err != nil { log.Fatal(err) } }
PS C:\GO_Language\file> go run truncate.go
-
Append Content in a Text File
package main import ( "fmt" "os" ) func main() { msg := "Add this content at end" fname := "test.txt" f, err := os.OpenFile(fname, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660) if err != nil { fmt.Println(err) os.Exit(-1) } defer f.Close() fmt.Fprintf(f, "%s\n", msg) }
Output :
PS C:\GO_Language\file> go run append.go
-
Change file permission, ownership, and timestamps
package main import ( "log" "os" "time" ) func main() { _, err := os.Stat("test.txt") if err != nil { if os.IsNotExist(err) { log.Fatal("File does not exist.") } } log.Println("File exist.") // Change permissions Linux. err = os.Chmod("test.txt", 0777) if err != nil { log.Println(err) } // Change file ownership. err = os.Chown("test.txt", os.Getuid(), os.Getgid()) if err != nil { log.Println(err) } // Change file timestamps. addOneDayFromNow := time.Now().Add(24 * time.Hour) lastAccessTime := addOneDayFromNow lastModifyTime := addOneDayFromNow err = os.Chtimes("test.txt", lastAccessTime, lastModifyTime) if err != nil { log.Println(err) } }
Output :
PS C:\GO_Language\file> go run change.go 2022/08/20 16:55:42 File exist. 2022/08/20 16:55:42 chown test.txt: not supported by windows
-
Compress a list of files into a ZIP file
package main import ( "archive/zip" "fmt" "io" "log" "os" ) func appendFiles(fname string, zipw *zip.Writer) error { file, err := os.Open(fname) if err != nil { return fmt.Errorf("Failed to open %s: %s", fname, err) } defer file.Close() wr, err := zipw.Create(fname) if err != nil { msg := "Failed to create entry for %s in zip file: %s" return fmt.Errorf(msg, fname, err) } if _, err := io.Copy(wr, file); err != nil { return fmt.Errorf("Failed to write %s to zip: %s", fname, err) } return nil } func main() { flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC file, err := os.OpenFile("test.zip", flags, 0644) if err != nil { log.Fatalf("Failed to open zip for writing: %s", err) } defer file.Close() var files = []string{"test1.txt", "test2.txt", "test3.txt"} zipw := zip.NewWriter(file) defer zipw.Close() for _, filename := range files { if err := appendFiles(filename, zipw); err != nil { log.Fatalf("Failed to add file %s to zip: %s", fname, err) } } }
Output :
PS C:\GO_Language\file> go run compress.go
-
Extract or Unzip
package main import ( "archive/zip" "io" "log" "os" "path/filepath" ) func main() { zipReader, _ := zip.OpenReader("test.zip") for _, file := range zipReader.Reader.File { zippedFile, err := file.Open() if err != nil { log.Fatal(err) } defer zippedFile.Close() tDir := "./" extractedFilePath := filepath.Join( tDir, file.Name, ) if file.FileInfo().IsDir() { log.Println("Directory Created:", extractedFilePath) os.MkdirAll(extractedFilePath, file.Mode()) } else { log.Println("File extracted:", file.Name) opFile, err := os.OpenFile( extractedFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode(), ) if err != nil { log.Fatal(err) } defer opFile.Close() _, err = io.Copy(opFile, zippedFile) if err != nil { log.Fatal(err) } } } }
Output :
PS C:\GO_Language\file> go run extract.go 2022/08/20 17:11:43 File extracted: test1.txt 2022/08/20 17:11:43 File extracted: test2.txt 2022/08/20 17:11:43 File extracted: test3.txt
-
The post Files and directories with examples appeared first on Prwatech.
This post first appeared on Learn Big Data Hadoop In Bangalore, please read the originial post: here