首页 > 解决方案 > 如果文件存在或默认字符串,则获取文件内容

问题描述

我检查doesFileExist filePathhandle <- 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

标签: haskellio

解决方案


像这样:

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实例。


推荐阅读