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
解决方案
像这样:
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
实例。
推荐阅读
- python - 如何在没有 ModuleNotFoundError 的情况下在 bash 中导入包
- flutter - Flutter:在屏幕上看不到 SVG 图片
- here-api - HERE 卫星地图 API 返回 400 错误请求
- c++ - 写入函数中的 CURL 缺少数据
- python - 如何在多线程中使用 tqdm?
- perl - 在 Perl 中使用 Grep 进行搜索
- database - 如何在 BigQuery 中显示存储过程的定义?
- angular - 使用 Angular Pipes 将一位数变成两位数
- python - Python列表中的不同
- laravel - 重命名迁移文件夹中的文件后,Laravel 未迁移