doushi1964 2019-06-20 01:19
浏览 150
已采纳

我想通过将文件名作为GoLang中的用户输入来读取文件

I have a JSON file called example.json. I need to read this file by taking its name as user input. I have tried with the below code.

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text,_ := reader.ReadString('
')


    fmt.Println(text)

    file,_ := ioutil.ReadFile(text)
    // os.Exit()
    fmt.Print(file)
}

But It's not working properly. I want to take the JSON file name as a command line input and read the JSON file.

I checked with the below method. But it's not matched with my case.

reader.ReadString does not strip out the first occurrence of delim

  • 写回答

1条回答 默认 最新

  • doutongxuan1614 2019-06-20 02:24
    关注

    First things first. You can figure out why your code doesn't work if you simply deal with the errors properly. You're ignoring the error thrown when you call iotuil.ReadFile(text). Just add the proper treatment and you will have a good clue why it isn't working

    file, err := ioutil.ReadFile(text)
    if err != nil {
        log.Fatal(err)
    }
    

    : no such file or directory

    The reason why your program does not work is likely because there's a break line character in your text variable.

    From Go Documentation

    "ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter."

    Remove the break like character from the variable that holds your user's input and it should work, assuming the input actually matches to a existing file including its correct path.

    func main() {
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Enter text: ")
        text, _ := reader.ReadString('
    ')
    
        text = strings.TrimSuffix(text, "
    ")
    
        //Add the file path
        //or else the user will be required to enter the entire file location
        f := "path_to_the_file" + text 
    
        file, err := ioutil.ReadFile(f)
    
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Println(string(file))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里