如果文件存在则获取文件内容或默认String

chr*_*eyn 1 io haskell

我检查,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
Run Code Online (Sandbox Code Playgroud)

Dan*_*ner 6

像这样:

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
Run Code Online (Sandbox Code Playgroud)

该const _ (e :: IOException)位只是为了能够提供e类型注释,以便catch知道Exception要使用哪个实例.