---
title: "java 操作配置文件 .properties"
author: "sgp420"
date: "2013-08-29T15:52:24Z"
tags: []
categories: ["Web前端"]
slug: "java-properties"
draft: false
lastmod: "2013-08-29T15:53:28Z"
id: 1933370
url: "https://sgp420.iteye.com/blog/1933370"
---

package com.dms.common;

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.util.Properties;

public class GetDayRandomNumber {

 private  Properties prop = new Properties();  
 private final  String path = "pageparam.properties";  
 private  String patha = "";  
   
 public GetDayRandomNumber(){  
  this.getFilePath();  
  this.loadFile();  
 }  
   
 private  void getFilePath(){   //获取配置文件的路径  
  patha = this.getClass().getClassLoader().getResource("").getPath()+"com/dms/config"+"/"+path;  
 }  
   
 public void loadFile(){//加载文件  
  FileInputStream in = null;  
  try {  
     
   File file = new File(patha);  
   in = new FileInputStream(file);  
   prop.load(in);  
     
  } catch (IOException e) {  
   e.printStackTrace();  
   throw new ExceptionInInitializerError();  
  } finally {  
   try {  
    in.close();  
   } catch (Exception e) {  
   }  
  }  
 }  
   
 public  void modifyValue(String key , String value){//修改文件  
  File file = new File(patha);  
  prop.setProperty(key, value);  
  FileOutputStream out;  
  try {  
   out = new FileOutputStream(file);  
   prop.store(out, "");//写入的格式  
  } catch (FileNotFoundException e) {  
   // TODO Auto-generated catch block  
   e.printStackTrace();  
  } catch (IOException e) {  
   // TODO Auto-generated catch block  
   e.printStackTrace();  
  }  
 }

   
 public  String getValue(String key) {   //直接通过主键获取对应的内容  
  return prop.getProperty(key);  
 }  
 }

1、主要注意的是 如果在开发平台运行 如

![](http://dl2.iteye.com/upload/attachment/0088/7451/f3c290a9-f473-3409-9e03-fe0947a0be47.png)  
 

则工程里面的文件是没有内容 如

![](http://dl2.iteye.com/upload/attachment/0088/7453/bbed8998-6152-3968-837e-aa5616e3a106.png)  
 

 

2、要看见内容，需要再打包后的工程里面找 如

![](http://dl2.iteye.com/upload/attachment/0088/7463/e495b68d-8011-3a2a-b1aa-b79386f796a4.png)  
 

 

3、顺便说下随机数的产生方法

3.1、问题：产生一个3位数的随机数(100--999)

3.2、思路：因为随机函数Random只能指定上限，却不能指定一个范围；

                  所以需要借用循环体来实现；

                  当满足条件时，跳出；不满足条件时，接着执行；

3.3、实现方法：

Random rd = new Random();  
   int random = 0;  
    do{  
     random = rd.nextInt(999);  
    }while(random&lt;100);

也可以将3位数分开分别产生，方法很多

 

 

**如有说错之处，请指出，相互学习，嘿嘿**