代码之家  ›  专栏  ›  技术社区  ›  christian wuensche

如果文件存在或默认字符串,则获取文件内容

  •  1
  • christian wuensche  · 技术社区  · 7 年前

    我检查 doesFileExist filePath 但是 我如何使用 handle <- openFile filePath ReadMode 仅当文件存在时

    或者,当文件不存在时,如何获取默认字符串?

    getFileContent filePath = do
        handle <- openFile filePath ReadMode
        content <- hGetContents handle
        return content
    
    main = do
        blacklistExists <- doesFileExist "./blacklist.txt"
        let fileContent = if not blacklistExists
                then ""
                else getFileContent "./blacklist.txt"
    
        putStrLn fileContent
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   Daniel Wagner    7 年前

    这样地:

    import Control.Exception
    
    getFileContentOrElse :: String -> FilePath -> IO String
    getFileContentOrElse def filePath = readFile filePath `catch`
        \e -> const (return def) (e :: IOException)
    
    main = getFileContentOrElse "" "blacklist.txt" >>= putStrLn
    

    这个 const _ (e :: IOException) 只是为了能够给予 e 类型注释,以便 catch 知道哪一个 Exception 要使用的实例。

        2
  •  4
  •   willeM_ Van Onsem    7 年前

    我们可以解决 编译程序错误 如下所述。问题是 getFileContent 是一个 IO String 反之 "" 只是一个 String . 我们可以使用 return :: Monad m => a -> m a 将数据包装到例如 IO .

    然后我们仍然需要“打开数据 输入输出字符串 当我们想打印时携带,这样我们可以更改 main 到:

    main = do
        blacklistExists <- doesFileExist "./blacklist.txt"
        fileContent <- if not blacklistExists
                then return ""
                else getFileContent "./blacklist.txt"
        putStrLn fileContent

    上面所说的不太“安全”。例如,在检查现有文件和打开文件之间,可能会有人删除该文件。文件也可能存在,但无法读取等。

    因此,最好使用 e 阿西尔 SK f ermission(eafp)“一种方法,在这种方法中,我们希望打开文件,如果出现问题,我们将返回空字符串,就像由 @DanielWagner .

    推荐文章