运用properties进行文件操作

package haohaoxuexi;

//利用properties输出到文件
//资源配置文件
import java.util.Properties;

public class lianxi18 {
public static void main(String[] args) {
//创建properties对象
Properties properties=new Properties();
//存储
properties.setProperty("driver", "oracle.jdbc.driver.OracleDrier");
//properties.setProperty("url", "jdbc:oracle:thin@localhost:1521:orcl");
properties.setProperty("user", "scott");
properties.setProperty("pwd", "tiger");
//获取
String string=properties.getProperty("url", "test");
System.out.println(string);
}

}

package haohaoxuexi;

import java.io.FileNotFoundException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/*使用properties
1.存储为.properties的文件
store(OutputStream out,String comments)
store(Writer writer,String comments)
2.存储为.xml的文件
storeToXML(OutputStream out,String comments)
storeToXML(OutputStream out,String comments,string encoding)
*/
public class lianxi19 {
public static void main(String[] args) throws FileNotFoundException, IOException {
//创建对象
Properties properties=new Properties();
//存储
properties.setProperty("driver", "oracle.jdbc.driver.OracleDrier");
properties.setProperty("url", "jdbc:oracle:thin@localhost:1521:orcl");
properties.setProperty("user", "scott");
properties.setProperty("pwd", "tiger");

//存储到绝对路径
properties.store(new FileOutputStream(new File("g:/db.properties")), "db配置");
properties.storeToXML(new FileOutputStream(new File("g:/db.xml")), "db配置");
//当前工程相对路径
properties.store(new FileOutputStream(new File("src/haohaoxuexi/db.properties")), "db配置");
}

}

package haohaoxuexi;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
//利用properties输出到文件
//资源配置文件
//使用load读取文件
public class lianxi20 {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties properties=new Properties();
//读取绝对路径
properties.load(new FileReader("g:db.properties"));
//读取相对路径
properties.load(new FileReader("db.properties"));
//输出读取到的文件
System.out.println(properties.getProperty("user", "bjsxt"));
}

}

 

package haohaoxuexi;

import java.io.IOException;
import java.util.Properties;
//利用properties输出到文件
//资源配置文件
//通过用get方法实现值的查找
//getProperty(string key,defultvalue);

public class lianxi21 {
public static void main(String[] args) throws IOException {
//新建
Properties properties=new Properties();
//从当前的类向上查找
properties.load(lianxi21.class.getResourceAsStream("/haohaoxuexi/db.properties"));
//从当前main方法向上查找
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("haohaoxuexi/db.properties"));
//输出
System.out.println(properties.getProperty("user","bjsxt"));

}

}

posted @ 2017-04-30 15:51  Dark~Clearlove  阅读(201)  评论(0编辑  收藏  举报