您的位置:首页 > 编程语言 > Java开发

java Properties类

2016-05-11 11:14 579 查看
/*
演示:如何将流中的数据存储到集合中
想要将info.txt中键值数据存到集合中进行操作。

思路:
1,用一个流和properties.txt文件关联。
2,读取一行数据,将该行数据用“=”进行分割。
3,等号左边作为键,右边作为值,存到Properties集合中。

注意:
对于split函数,如果分隔符为“.”或“|”或“+”等本身为转义字符时,要使用转义字符\\
即,str.split("\\.");
str.split("\\|");
*/
import java.io.*;
import java.util.*;
class  PropertiesTest
{
public static void main(String[] args) throws IOException
{
method();
}

public static void method() throws IOException
{
BufferedReader br=new BufferedReader(new FileReader("D:\\myfile\\mycode\\properties.txt"));

FileOutputStream fos=new FileOutputStream("D:\\myfile\\mycode\\properties.txt",true);
Properties prop=new Properties();

String line=null;
while((line=br.readLine())!=null)
{
sop(line.split("\\+")[0]);
String key=line.split("\\+")[0];
String value=line.split("\\+")[1];
prop.setProperty(key,value);
}
prop.store(fos,"haha");
sop(prop);
br.close();
fos.close()
}

public static void sop(Object obj)
{
System.out.println(obj);
}
}


/*
配置文件,统计程序运行的次数,当程序运行一定的次数后,提示不能再使用.
注意Properties类中的几个方法:
load(InputStream inStream);// 从输入流中读取属性列表(键和元素对)。
store(OutputStream outStream,String comments);// 以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,
//将此 Properties 表中的属性列表(键和元素对)写入输出流。
//其中comments是注释。
*/
import java.io.*;
import java.util.*;
class RunCount
{
public static void main(String[] args) throws IOException
{
runCount();
}

public static void runCount() throws IOException
{
File file=new File("D:\\myfile\\mycode\\count.ini");
if(!file.exists())
file.createNewFile();

FileInputStream fis=new FileInputStream(file);

Properties prop=new Properties();
prop.load(fis); //将读取的目标文件加载到属性对象中
int count=0;
String value=prop.getProperty("time");
if(value!=null)
{
count=Integer.parseInt(value);
if(count>=5)
{
System.out.println("运行次数已大于5次");
return ;
}
}
count++;
prop.setProperty("time",count+"");
FileOutputStream fos=new FileOutputStream(file);
prop.store(fos,"");//将属性对象中的内容存储到输出文件中

fis.close();
fos.close();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java Properties类