---
title: "Clojure 读取 保存 对象"
author: "lippeng"
date: "2013-03-22T15:26:58Z"
tags: []
categories: ["编程语言"]
slug: "clojure"
draft: false
lastmod: "2013-03-22T15:26:58Z"
id: 1834885
url: "https://lippeng.iteye.com/blog/1834885"
---

读《实用Common Lisp编程》时，读到 可以把Lisp数据结构直接持久化到文件中，之后，可以从该文件中读回Lisp对象，同时，文件中存储的内容是Lisp形式，和XML一样，是人可读的，觉得很赞。

 

Clojure中一样也可以这么做，并且非常简单。

 

1、把一个Clojure的Map保存的文件 hello.txt中：

```
user=> (spit "hello.txt" {:name "Hello, World!", :age "120"})
nil
```

 

2、打开文件hello.txt，发现其中内容：

```
{:age "120", :name "Hello, World!"}
```

 

3、从hello.txt中读回：

```
user=> (load-file "hello.txt")
{:age "120", :name "Hello, World!"}
```

 

4、不相信这是Clojure的对象？

```
user=> (class (load-file "hello.txt"))
clojure.lang.PersistentArrayMap
```

 

这功能简单实用！想到曾经用Java读写XML，各种揪心。。。