---
title: "Java的properties读取和写入"
author: "rocketa"
date: "2013-09-19T10:01:49Z"
tags: []
categories: ["编程语言"]
slug: "java-properties"
draft: false
lastmod: "2013-09-19T10:01:49Z"
id: 1944148
url: "https://rocketa.iteye.com/blog/1944148"
---

properties应该算是比较常用的东西了，它能自动把文件中的行转换成键值对的关系，提供给用户使用。

读取：

```
Properties p=new Properties(); 
p.load(new FileInputStream(file));
String userName = p.getProperty("userName");
```

 当然，其中的new FileInputStream(file)可以替换成你需要的形式。

 

写入：

```
Properties p=new Properties(); 
p.load(new FileInputStream(file));
p.put("userName", "rocketa");
p.store(new FileOutputStream(file), "comment");
```

 其中第2行先load一次，为的是在写文件的时候把原来的properties保留下来。